1

I have a set of fields:

fieldName1
fieldName2
fieldName3
fieldName4
fieldName5

and I want to be able to create a for loop something like this:

{% for i in 1..5 %}
    {% if entry.fieldName ~ i|length %}
    …
    {% endif %}
{% endfor %}

I've seen other answers mention the attribute function, but when I try something like this:

{% for i in 1..5 %}
    {% if entry.attribute(_context['fieldName' ~ i])|length %}
    …
    {% endif %}
{% endfor %}

I get:

Key "fieldName1" for array with keys "entry, variables, craft, currentSite, currentUser, siteName, siteUrl, systemName, view, devMode, … i, _key" does not exist.

How should it be?

1 Answer 1

2

Maybe you can try like this, attribute you seek is twig function not from the craft entry value.

{% for i in 1..5 %}
 {% set field = attribute(entry,'fieldName' ~ i) %}
 {% if field is defined and field|length %}
    …
 {% endif %}
{% 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.