如何将参数传递给使用'include'渲染的PHP模板?

17

我需要你们的帮助来处理 PHP 模板。我是 PHP 初学者(我之前使用的是 Perl+Embperl)。我的问题很简单:

  • 我有一个小模板,用于渲染一些项目,比如博客文章。
  • 我唯一知道如何使用这个模板的方法是使用 'include' 指令。
  • 我想在遍历所有相关的博客文章时调用此模板。
  • 问题: 我需要向该模板传递参数;在这种情况下是一个表示博客文章的数组的引用。

代码大致如下:

$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;
}
任何想法如何完成这个?我真的被难住了:)还有其他方法来呈现模板吗?

有没有任何想法如何完成这件事?我真的被卡住了 :) 还有其他方法可以呈现模板吗?

3个回答

34
考虑将一个 PHP 文件包含进来,就像你将代码从 include 复制粘贴到 include 语句所在的位置一样。这意味着你继承了当前的范围。因此,在您的情况下,$param 已经在给定的模板中可用。

1
为了增加不同的效果,尝试从你的include语句中返回一个值(return 42;),并捕获该值:$result = include 'filethatreturns42.php'; ;) - NSSec
还有一个问题是,如果您想调用模板加载器上可见的函数,则必须在模板中再次引用它,否则会触发错误。 - Toni Michel Caubet

25

$param应该已经在模板中可用了。当您使用include()包含文件时,它应该具有与包含它的位置相同的作用域。

来自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。


非常好,谢谢!是的,我更喜欢使用哈希作为参数,这样函数在未来很容易修改。 - Uruloki
这就是像CodeIgniter这样的框架的工作原理。您加载一个模板文件并将一个值数组传递给它,这些值被提取并在模板中使用。 - Jake Wilson

3

当我处理简单的网站时,我使用以下辅助函数:

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);
}

display会直接将模板输出到屏幕上。render则以字符串形式返回它。它使用ob_get_contents函数来返回打印函数的输出。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接