dsn46282 2009-10-27 20:35
浏览 29
已采纳

与RoR模板partials / collections相当的PHP

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.

  • 写回答

2条回答 默认 最新

  • dream518518518 2009-10-27 22:50
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作