PHP equivalent for RoR template partials/collections

独自空忆成欢 提交于 2019-12-11 07:36:26

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1633494/php-equivalent-for-ror-template-partials-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!