簡體   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