我有一个叫做load_template()的函数
这个函数有两个参数
我希望这件事成功的方式是。
在模板('test')中,我希望能够编写
<?php echo $title; ?>然后打电话
load_template('test', array('title' => 'My Title'));把它填好。
我该怎么做?
输出缓冲方法。I已经给出了下面的代码。
我相信这是可以改进的。
public static function template($name, $vars = array()) {
if (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;
}发布于 2011-01-20 20:31:55
发布于 2011-01-20 20:32:07
像这样吗?
function load_template($name, $vars)
{
include('template/'.$name.'.tpl'); //.tpl, .inc, .php, whatever floats your boat
}在template/whatever.tpl中,你会发现:
...
<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; ?>
...当然,这假设输出是直接打印出来的。您可以直接打印tpl文件,或者生成一个字符串,或者缓冲tpl文件的输出并从load_template返回它。
https://stackoverflow.com/questions/4752177
复制相似问题