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

14 php parameters templates include

需要你的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;
}
Run Code Online (Sandbox Code Playgroud)

任何想法如何实现这一目标?我真的很难过:)有没有其他方法来渲染模板?

NSS*_*Sec 33

考虑包含一个PHP文件,就好像您将包中的代码复制粘贴到include-statement所在的位置.这意味着您继承了当前范围.

因此,在您的情况下,$ param已在给定模板中可用.


Tom*_*igh 22

$ 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.
Run Code Online (Sandbox Code Playgroud)

然后$ row可用,但仍称为$ row.