RoR 模板部分/集合的 PHP 等效项 [英] PHP equivalent for RoR template partials/collections

查看:52
本文介绍了RoR 模板部分/集合的 PHP 等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出为我正在编写的 PHP 模板类实现 RoR 样式部分/集合的最有效方法.对于那些不熟悉 rails 的人,我想遍历位于单独文件中的模板片段(例如表行或列表项).我想做到这一点而无需求助于 eval 或在循环中放置一个包含.

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.

我看过类似的帖子解决了单个部分,这是微不足道的,但没有涵盖在集合中实现部分.我一直在考虑这个问题,我的头很痛,恐怕我忽略了一个明显的解决方案.我希望这里有人可以提出一个优雅的解决方案,同样,不需要 eval 或包含在循环中.TIA.

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.

推荐答案

您需要一个模板引擎,它可以自行处理包含,然后立即评估整个内容.很像 c 预处理器的工作原理.

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.

第 1 步(源模板):

Step 1 (source template):

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

第 2 步(预处理后):

Step 2 (after preprocessing):

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

第 3 步(最终渲染)

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.

这篇关于RoR 模板部分/集合的 PHP 等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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