繁体   English   中英

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

[英]How to pass parameters to PHP template rendered with '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;
}

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

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

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

$ 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。

我在简单网站上工作时使用以下帮助函数:

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返回函数的打印输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM