首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将参数传递给用“include”呈现的PHP模板?

如何将参数传递给用“include”呈现的PHP模板?
EN

Stack Overflow用户
提问于 2009-08-21 14:29:37
回答 3查看 30.7K关注 0票数 17

需要您在PHP模板方面的帮助。我对PHP很陌生(我来自Perl+Embperl)。总之,我的问题很简单:

我有一个小模板来呈现某个项目,让它成为一个博客文章。我知道使用这个模板的唯一方法是使用‘’指令。我想在循环中调用这个模板的

  • ,我需要向这个模板传递一个参数;在这个例子中,引用代表博客帖子的数组。

代码如下所示:

代码语言:javascript
复制
$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;
}

有什么办法做到这一点吗?我真的很困惑:)还有其他方法来呈现模板吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-08-21 14:31:20

考虑将PHP文件作为复制粘贴代码从include到包含语句所在的位置。这意味着继承当前范围。

因此,在您的示例中,$param已经在给定的模板中可用。

票数 34
EN

Stack Overflow用户

发布于 2009-08-21 14:32:04

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

来自http://php.net/manual/en/function.include.php

当包含文件时,它包含的代码继承包含包含的行的变量范围。从那时起,调用文件中该行中的任何可用变量都将在被调用文件中可用。但是,所包含的文件中定义的所有函数和类都具有全局范围。

你也可以这样做:

代码语言:javascript
复制
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。

票数 25
EN

Stack Overflow用户

发布于 2012-12-14 02:43:20

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

代码语言:javascript
复制
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返回函数的打印输出。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1312300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档