<p>Maybe you can try like this, attribute you seek is twig function not from the craft entry value.</p>
<pre><code>{% for i in 1..5 %}
 {% set field = attribute(entry,'fieldName' ~ i) %}
 {% if field is defined and field|length %}
    …
 {% endif %}
{% endfor %}
</code></pre>

CC BY-SA 4.0
2022-01-04T07:16:19.177Z
2022-01-04T07:16:19.177Z
aodihis
<p>I have a set of fields:</p>
<pre><code>fieldName1
fieldName2
fieldName3
fieldName4
fieldName5
</code></pre>
<p>and I want to be able to create a <code>for</code> loop something like this:</p>
<pre><code>{% for i in 1..5 %}
    {% if entry.fieldName ~ i|length %}
    …
    {% endif %}
{% endfor %}
</code></pre>
<p>I've seen other answers mention the <code>attribute</code> function, but when I try something like this:</p>
<pre><code>{% for i in 1..5 %}
    {% if entry.attribute(_context['fieldName' ~ i])|length %}
    …
    {% endif %}
{% endfor %}
</code></pre>
<p>I get:</p>
<blockquote>
<p>Key &quot;fieldName1&quot; for array with keys &quot;entry, variables, craft, currentSite, currentUser, siteName, siteUrl, systemName, view, devMode, … i, _key&quot; does not exist.</p>
</blockquote>
<p>How should it be?</p>

<templating><forloop><variable>
For loop to dynamically output field names
# For loop to dynamically output field names

(Asked by: username_0 on 2022-01-04)

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?

**Tags:** templating, forloop, variable

---

## 1 answers

### Answer by username_1 on 2022-01-04. Score: 2 | Accepted answer

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 %}


---

