Michael Lynch Michael Lynch - 1 year ago 166
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
index from the for loop in the name of an object property?

Answer Source

You have several ways:


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


    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download