Ros*_*oss 2 php variables templates global-variables
我在PHP中编写了一个简单的模板层,但是我有点陷入困境.以下是它的工作原理:
首先,我使用fetch_template从数据库加载模板内容 - 这是有效的(如果你感兴趣,我会在启动时收集所有模板).
我在模板代码和逻辑中使用PHP变量 - 例如:
// PHP:
$name = 'Ross';
// Tpl:
<p>Hello, my name is $name.</p>
Run Code Online (Sandbox Code Playgroud)
然后我使用output_template(下面)解析模板中的变量并替换它们.以前我使用模板标签和美化str_replace模板类,但效率太低.
/**
* Returns a template after evaluating it
* @param string $template Template contents
* @return string Template output
*/
function output_template($template) {
eval('return "' . $template . '";');
}
Run Code Online (Sandbox Code Playgroud)
我的问题,如果你还没有猜到,是变量没有在函数内声明 - 因此函数不能解析它们,$template除非我把它们放在全局范围内 - 我不确定我想做什么.那个或者有一个变量数组作为函数中的参数(听起来更乏味但可能).
有没有人在我的代码中使用函数代码(它只是一个单行代码)而不是使用函数?
谢谢,罗斯
Ps我知道Smarty和那里的各种模板引擎 - 我不打算使用它们所以请不要建议它们.谢谢!
小智 7
您可以使用而不是通过循环include($template_name).
或者,如果您想要模板输出的内容,您可以执行以下操作:
$template_name = 'template.php';
// import the contents into this template
ob_start();
include($template_name);
$content = ob_get_clean();
// do something with $content now ...
Run Code Online (Sandbox Code Playgroud)
请记住,在您的模板中,您可以使用经常被忽视的PHP语法:
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
Run Code Online (Sandbox Code Playgroud)
替代语法可用于if,while,for,foreach和switch ...非常适合操作模板中的数据.有关更多详细信息,请参阅" 控制结构的替代语法 ".
我传递一个带变量的关联数组来替换,然后解析它们.
然后你也可以通过$ _GLOBALS来实现相同的结果.
function output_template($template, $vars) {
extract($vars);
eval('return "' . $template . '";');
}
Run Code Online (Sandbox Code Playgroud)
编辑:您可能还需要考虑字符串替换而不是eval,具体取决于允许编写模板的人员以及指定要加载的模板的人员.那么逃避也可能存在问题......