dtfo55908 2011-10-20 13:47
浏览 32
已采纳

Twig - 在父级中使用多个子模板

I have the following two templates

parent.html

<ul class="basketItems">
    {% for item in items %}
        {{ item | raw }}
    {% endfor %}
</ul>

child.html

<li>
    <a href="/go/to/my/page">{{ link.title}}</a>
</li>

Now i would like to have multiple instances of child.html within parent.html. In My php code I have to loop through the children and pass in the link object so that the link.title variable can be populated.

My current code involves me loading in parent.html, then rendering each child and creating a php array, then rendering the parent.html and passing in all the generated html of the children as array entries (see below). Is there any easy way to do this without having to build up a php array of html snippets by possibly using Twig blocks.

$parent = $twig->loadTemplate("parent.html");
foreach ($items as $item) {
    $child = $twig->loadTemplate("child.html");
    var $link = link::get($item->id));
    /* do some other database retreival / data processing work */

    $childHtml[] = $child->render(array('item' => $link));
}
$parent->render(array('items' => $childHtml));

Thanks in advance

  • 写回答

1条回答 默认 最新

  • dongying7667 2011-10-20 13:51
    关注

    try this:

    {% for item in items %}
        {% include "child.html" %}
    {% endfor %}
    

    Here in Manual: http://twig.sensiolabs.org/doc/templates.html

    And for PHP Part:

    $parent = $twig->loadTemplate("parent.html");
    
    
    for ($i =0; $i < count($items); $i++) {
    
        /* do some other database retreival / data processing work */
    
        /* add additional information to array */
        $items[i]['link'] = link::get($item->id));      
    }
    $parent->render(array('items' => $childHtml));
    

    Do the controller stuff and pass that clean array to template engine. Don't mix that.

    It is always better to follow "Separation of concerns" principle: http://en.wikipedia.org/wiki/Separation_of_concerns

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里