Twig extract FOR loop variables

时间:2016-03-16 11:33:27

标签: twig symfony

Say I have a collection of items

$collection = array(
      'item1' => array(
            'post' => $post,
            'category' => $category,
            // ...
  ),
  'item2' => array(...)
);

And I have a template:

{% for item in collection %}

    Now I can use item data
       - {{ item.post.title }}
       - {{ item.category.id }}
       - {{ item.var1 }}
       - {{ item.var2 }}
       - and another 20 vars

    I want to extract those vars into more global FOR context, and use them as:

        {{ post.title }}
        {{ category.id }}
        {{ var1 }}
         ... etc

{% endfor %}

Is this possible?

I was thining of defining the loop as a template block and then iterating it with Twig_Template::renderBlock(). But the docs say renderBlock is for 'internal' use only :) So not sure.

EDIT:

Another idea I had:

{% for item in collection %}

    {% do extract(item) %}
    // extract() would work similar to extract function from php

{% endfor %}

However, it seems that context is passed to twig functions by value, so this would not work.

Lastly I could write a TokenParser and do:

{% for item in collection %}

    {% extract item %}
    // would probably get direct access to the context, but haven't tried it

{% endfor %}

But this is quite a bit of work.. I am just hoping that twig can already do this natively :)

2 个答案:

答案 0 :(得分:1)

您可以使用宏: http://twig.sensiolabs.org/doc/tags/macro.html

{% import _self as macro %}

{% macro render(item) %}
    {{ item.post.title }}
    {{ item.category.id }}
    {{ item.var1 }}
    {{ item.var2 }}
    ...
{% endmacro %}

{% for item in collection %}
   {{ macro.render(item) }}
{% endfor %}

答案 1 :(得分:0)

如果您真的想在全局上下文中分配变量:

{% for item in collection %}
    {% for var, value in item %}
        {% set  _context[var] = value %}
    {% endfor %}

    {{ post.title }}
    {{ category.id }}
    {{ var1 }}
     ... etc
{% endfor %}