php:简单的模板引擎
我有一个名为 load_template()
的函数,
该函数有两个参数
- $name =>模板的名称
- $vars =>键数组 =>模板中要替换的值变量。
我希望这个工作的方式是。
在模板(“测试”)中,我希望能够编写
<?php echo $title; ?>
然后调用
load_template('test', array('title' => 'My Title'));
并填写它。
我该怎么做?
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 (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;
}
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 (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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用 ob_start 和 ob_get_clean 如果您想捕获变量中的输出。
Wrap with ob_start and ob_get_clean if you want to capture the output in a variable.
像这样的东西吗?
在
template/whatever.tpl
中,您会得到:当然,这是假设直接打印输出。
您可以直接打印 tpl 文件,或者生成字符串,或者缓冲 tpl 文件的输出并从
load_template
返回它Something like this?
and in
template/whatever.tpl
you'd have: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