views:

571

answers:

2

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

  • 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.

Code looks something like this:

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

+9  A: 

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.

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

MathieuK
+1 the copy-paste analogy is always how I explain it.
Peter Bailey
Holy shit, it does really work! Wow, it's so simple and yet so different from what i'm accustomed to with .net or perl+emberl.
Uruloki
For added differentness, try returning a value (`return 42;`) from your include and capturing that value: `$result = include 'filethatreturns42.php';` ;)
MathieuK
+3  A: 

$param should be already available inside the template. When you include() a file it should have the same scope as where it was included.

from http://php.net/manual/en/function.include.php

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

You could also do something like:

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);
   include($template);
   //etc.

Then $row would be available, but still called $row.

Tom Haigh
Very nice, thanks! Yes, i prefer to use hashes as params so that function is easily modifiable in the future.
Uruloki