Jump to content

Recommended Posts

Here is a really simple way you can do it:

 

<?php
function load_template($tpl_name, array $arguments = array())
{
foreach($arguments as $key => $value)
{
	if($key == 'tpl_name') continue; // don't break it

	$$key = $value;
}

ob_start();
eval('?>' . file_get_contents('templates/' . $tpl_name . '.tpl.php'));
$output = ob_get_contents();
ob_end_clean();

return $output;
}

echo load_template('test', array('title'=>'Test page', 'username'=>'Daniel'));
?>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<title><?php echo $title ?></title>
</head>
<body>

<h1><?php echo $title ?></h1>

<p>Hello <?php echo $username ?></p>

</body>
</html>

 

Output:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<title>Test page</title>
</head>
<body>

<h1>Test page</h1>

<p>Hello Daniel</p>

</body>
</html>

 

Note: The syntax highlighting broke, but it does work.

 

 

It doesn't really matter what you call your template files, PHP will parse it anyways. Some people just prefer to have a .tpl extension, you can use .php, .html or whatever you'd like.

Thank you very much for your kind reply,Daniel0. It is very helpful to me.

What I intend to do is do it in a modular fashion, with MVC pattern, ya, but I don't want to try the template engines like cakephp, smarty, etc. I would to create one on my own, also to cater for my own needs.

Ok, let's say, in my template, there will be head section, menu section,sidebar section,main content section,footer section,etc,what I am trying to do now is to build a separate .tpl file for each section, but with customizable functionality, i.e. when applying the template head, I shall be able to specify the title of the page.

What do you think of my approach? Any suggestions? It is still in my mind, I haven't have clear thoughts how to realize it in codes. So inputs would be greatly appreciated! 

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.