Michael Lynch Michael Lynch - 1 month ago 7
Twig Question

How can I use the index from a Twig for loop in the name of an object property?

I'm trying to use the index of a for loop in the property names of an object. Is this possible?

{% for i in 0..20 %}

{% include 'template.twig' with {
title: object.property_{{i}}_title,
length: object.property_{{i}}_length,
width: object.property_{{i}}_width
} %}

{% endfor %}


This results in a Twig error. Is it possible to use the
i
index from the for loop in the name of an object property?

Answer

You have several ways:

Interpolation:

{%
    include 'template.twig' with {
        title: object["property_#{i}_title"],
        length: object["property_#{i}_length"],
        width: object["property_#{i}_width"]
    } 
%}

Concatenation:

{%
    include 'template.twig' with {
        title: object["property_"~i~"_title"],
        length: object["property_"~i~"_length"],
        width: object["property_"~i~"_width"]
    } 
%}

or the attribute function (/cc comment from @DarkBee):

{%
    include 'template.twig' with {
        title: attribute(object, 'property_'~i~'_title'),
        length: attribute(object, 'property_'~i~'_length"),
        width: attribute(object, 'property_'~i~'_width'),
    } 
%}

See a live demo on twigfiddle.