php: simple template engine
I have a function called load_template()
this function has two parameters
- $name => the name of the template
- $vars => array of key => value variables to be replaced in the template.
the way I want this to work is.
in the template ('test') I want to be able to write
<?php echo $title; ?>
then call
load_template('test', array('title' => 'My Title'));
and have it fill it out.
how can I do this?
Output buffering method. I have come up with the code below. I am sure it can be improved.
public static function template($name, $vars = array()) {
if (开发者_JAVA技巧is_file(TEMPLATE_DIR . $name . '.php')) {
ob_start();
extract($vars);
require(TEMPLATE_DIR . $name . '.php');
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
throw new exception('Could not load template file \'' . $name . '\'');
return false;
}
function load_template($name, $vars)
{
extract($vars);
include $name;
}
Wrap with ob_start and ob_get_clean if you want to capture the output in a variable.
Something like this?
function load_template($name, $vars)
{
include('template/'.$name.'.tpl'); //.tpl, .inc, .php, whatever floats your boat
}
and in template/whatever.tpl
you'd have:
...
<title><?php echo $vars['title'] ?></title>
...
...
<?php if (!empty($vars['content'])): //template still needs to know if the content is empty to display the div ?>
<div id="content">
<?php echo $vars['content']; ?>
</div>
<?php endif; ?>
...
Of course, that assumes the output being printed directly.
You could have the tpl file print directly, or produce a string, or buffer the output from the tpl file and return it from load_template
精彩评论