views:

129

answers:

2

Hi, I'm trying to figure out the most efficient way to implement RoR-style partials/collections for a PHP template class that I'm writing. For those who aren't familiar with rails, I want to iterate over a template fragment (say a table row or list item) located in a separate file. I want to do this without resorting to eval or placing an include within the loop.

I've seen a similar post that addresses single partials, which are trivial, but nothing that covers implementing partials in a collection. I've been thinking about this so long my head hurts and I'm afraid I'm overlooking an obvious solution. I'm hoping someone here can suggest an elegant solution that, again, doesn't require eval or include within the loop. TIA.

A: 

You're asking how to do something without resorting to the solution.

Any template system you use is going to use an eval or an include within the loop, even if it's buried in abstraction 1000 layers deep.

That's just how it's done.

Darn... I was hoping there was some kind of trick I overlooked. I guess the question then becomes, in a collection containing 50 or 100 rows which method is more common/efficient, eval or include? I'm guessing eval?
shinjin
A: 

You need a templating engine with that can process includes on its own and then eval the whole thing at once. Much like c preprocessor works.

Step 1 (source template):

$template = '
   foreach($bigarray as $record)
       #include "template_for_record.php"
'

Step 2 (after preprocessing):

$template = '
   foreach($bigarray as $record)
       // include statement replaced with file contents
       echo $record['name'] etc
'

Step 3 (final rendering)

  // eval() only once
  eval($template);

In this way you can avoid the overhead of evaling/including subtemplate on every loop step.

stereofrog
A light-bulb just went on in my head. Great answer. Thanks a lot!
shinjin