如何将参数传递给使用'include'呈现的PHP模板? [英] How to pass parameters to PHP template rendered with 'include'?

查看:351
本文介绍了如何将参数传递给使用'include'呈现的PHP模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要你的PHP模板帮助。我是PHP的新手(我来自Perl + Embperl)。无论如何,我的问题很简单:

need your help with PHP templating. I'm new to PHP (I'm coming from Perl+Embperl). Anyway, my problem is simple:


  • 我有一个小模板来渲染一些项目,让它成为博客文章。

  • 我知道使用此模板的唯一方法是使用'include'指令。

  • 我想通过所有相关博客在循环中调用此模板帖子。

  • 问题:我需要将参数传递给此模板;在这种情况下引用代表博客文章的数组。

  • I have a small template to render some item, let it be a blog post.
  • The only way i know to use this template is to use 'include' directive.
  • I want to call this template inside a loop going thru all the relevant blog posts.
  • Problem: I need to pass a parameter(s) to this template; in this case reference to array representing a blog post.

代码看起来像这样:

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

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

Any ideas how to accomplish this? I'm really stumped :) Is there any other way to render a template?

推荐答案

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

Consider including a PHP file as if you were copy-pasting the code from the include into the position where the include-statement stands. This means that you inherit the current scope.

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

So, in your case, $param is already available in the given template.

这篇关于如何将参数传递给使用'include'呈现的PHP模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆