2

I'm looping through the rows of a table field and hoping to target a specific field entry based on the loop.index. Here's a simplified example of what that might look like:

{% for row in entry.table %}   
   {% set foo = entry.field ~ loop.index %}
{% endfor %}

The doesn't work, but I’m curious if I just have the syntax wrong or if I’m thinking about this the wrong way.

2 Answers 2

1

You can use the subscript syntax:

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

or the attribute function:

{{ attribute(entry, 'field' ~ loop.index) }}

The attribute function is more Twig-like in my opinion. But in this case it's only a matter of preference.

Other examples are:

{{ myArray[0] }} vs. {{ myArray|first }}
{{ myString[0:1] }} vs. {{ myString|slice(0, 1) }}

0
1

Turns out Twig has a nifty little attribute function that does the trick. Here's how it works:

{% for row in entry.table %}   
   {% set foo = attribute(entry, 'fieldHandle' ~ loop.index) %}
{% endfor %}

Big hat tip to Mr. Brad Bell for posting the original answer in Stack Exchange.

2
  • You could also just use the subscript syntax: entry['field' ~ loop.index].
    – carlcs
    Commented Nov 6, 2015 at 19:18
  • @carlcs I thought there might be a simpler way to accomplish that. That works like a charm and, to me, is a more elegant answer. You should post it so I can vote for it! Commented Nov 6, 2015 at 21:33

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.