需要您在PHP模板方面的帮助。我对PHP很陌生(我来自Perl+Embperl)。总之,我的问题很简单:
我有一个小模板来呈现某个项目,让它成为一个博客文章。我知道使用这个模板的唯一方法是使用‘’指令。我想在循环中调用这个模板的
代码如下所示:
$rows = execute("select * from blogs where date='$date' order by date DESC");
foreach ($rows as $row){
print render("/templates/blog_entry.php", $row);
}
function render($template, $param){
ob_start();
include($template);//How to pass $param to it? It needs that $row to render blog entry!
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}有什么办法做到这一点吗?我真的很困惑:)还有其他方法来呈现模板吗?
发布于 2009-08-21 14:31:20
考虑将PHP文件作为复制粘贴代码从include到包含语句所在的位置。这意味着继承当前范围。
因此,在您的示例中,$param已经在给定的模板中可用。
发布于 2009-08-21 14:32:04
$param应该已经在模板中可用了。当您包含()一个文件时,它应该具有与包含它的位置相同的作用域。
来自http://php.net/manual/en/function.include.php
当包含文件时,它包含的代码继承包含包含的行的变量范围。从那时起,调用文件中该行中的任何可用变量都将在被调用文件中可用。但是,所包含的文件中定义的所有函数和类都具有全局范围。
你也可以这样做:
print render("/templates/blog_entry.php", array('row'=>$row));
function render($template, $param){
ob_start();
//extract everything in param into the current scope
extract($param, EXTR_SKIP);
include($template);
//etc.那么$row是可用的,但仍被称为$row。
发布于 2012-12-14 02:43:20
在简单网站上工作时,我使用下列帮助函数:
function function_get_output($fn)
{
$args = func_get_args();unset($args[0]);
ob_start();
call_user_func_array($fn, $args);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
function display($template, $params = array())
{
extract($params);
include $template;
}
function render($template, $params = array())
{
return function_get_output('display', $template, $params);
}显示器将直接将模板输出到屏幕上。呈现将以字符串的形式返回。它使用ob_get_contents返回函数的打印输出。
https://stackoverflow.com/questions/1312300
复制相似问题