سؤال

I have two arrays that I loop through, but they are nested. Reduced to the minimum, it looks like this:

{% for item in items %}
    <label>{{ item.name }}</label>

    <select>
    {% for attribute in attributes %}
        <option>{{ attribute.name }}</option>
    {% endfor %}
    </select>

{% endfor %}

The problem is the size of the arrays. There are about 1,100 items and 400 attributes. As one can guess, this is slow. Very slow.

Is it possible to "store" the inner loop, and just reuse the generated/rendered block?

هل كانت مفيدة؟

المحلول

Move the inner loop outside of the outer loop and then store the value generated in a Twig variable. Then run the outer loop supplying the variable between the <select> tags. This way you only generate the inner loop once.

{% set options = '' %}
{% for attribute in attributes %}
    {% set options = options ~ '<option>' ~ attribute.name ~ '</option>' %}
{% endfor %}

{% for item in items %}
    <label>{{ item.name }}</label>
    <select>
        {{ options }}
    </select>
{% endfor %}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top