9

Let's say I have 5 Craft fields named "item1" thru "item5."

Instead of writing out each variable...

{{ entry.item1 }}
{{ entry.item2 }}
{{ entry.item3 }}
{{ entry.item4 }}
{{ entry.item5 }}

How can I create a loop to do this for me?

I've tried this...

{% for i is 1..5 %}

    {{ entry.item ~ loop.index }}

{% endfor %}

But it returns the error:

Craft\EntryModel and its behaviors do not have a method or closure named "item".

1 Answer 1

8

I found the answer in the Twig documentation: http://twig.sensiolabs.org/doc/templates.html#variables

You can use a dot (.) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array), or the so-called "subscript" syntax ([]):

{{ foo.bar }}
{{ foo['bar'] }}

When using the subscript syntax, you can concatenate the loop.index like so:

{% for i is 1..5 %}

    {{ entry['item' ~ loop.index] }}

{% endfor %}

Or even simpler, use the i variable from the for loop.

{% for i is 1..5 %}

    {{ entry['item' ~ i] }}

{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.