Pergunta

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

Foi útil?

Solução

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top