Jump to content

Recommended Posts

Basically I just need a quick, easy and simple way of separating my PHP code from my HTML code. So I wanna have one file with all the HTML and one file with the PHP code, linked via an include.

 

I'm not after a whole templating system like Smarty, just something simple that I can code by myself. Are there any online tutorials on how to do this?

Link to comment
https://forums.phpfreaks.com/topic/173611-separate-php-from-html/
Share on other sites

You could do something really simple like this:

 

$templateObjects = Array('somefile' => Array('{REPLACE_ME1}', '{REPLACE_ME2}'));

class Template 
{
private $template;

function __construct($title)
{ 
	$this->template = str_replace('{TITLE}', $title, file_get_contents('template/html/main.html'));
}

public function setContent($section, $content)
{
	$this->template = str_replace($section, $content, $this->template);
	return true;
}

public function display()
{
	echo $this->template;
	return true;
}
}

function getContent($template, $content)
{
global $templateObjects;

$structure = @file_get_contents('template/html/' . $template . '.html');
if(!$structure) return 'Error: Invalid template id (' . $template . ')';
return str_replace($templateObjects[$template], $content, $structure);
}

 

Then to use it:

 

template/html/main.html

defining your doctype etc.. everything that will be the same on every page..
<head>
<title>
{TITLE}
</title>
<html>
<body>
{MAIN_CONTENT}
</body>
</html>

 

template/html/somefile.html

This is some file.. {REPLACE_ME1} {REPLACE_ME2}

 

file.php

//Include class file
$template = new Template('Some title');
$content = getContent('somefile', Array('Hello', 'World'));
$template->setContent('{MAIN_CONTENT}', $content);
$template->display();

 

It's just a quick example, should you get started.

No Frameworks, no templating systems. Just a short piece of code that will do the job for me, I hope!

 

There is no such thing. You can separate programming logic from presentation logic through good design, this however is not the same as removing php completely from markup. To do that, you must use a template engine of some sort which just adds extra overhead really.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.