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 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染