7

I have the following code which works fine. I'm just wondering if there is a more simple way of incrementing the id number?

{% set counter = '1' %}
{% for block in entry.news %}
  {% if block.type == "bodyBlock" %}
    {{ block.body }}
  {% elseif block.type == "codeBlock" %}
  {% set counter = counter + 1%}
    <div id="accordion{{ counter }}">
    ...
    </div>
  {% endif %}
{% endfor %}
14

By using the default filter you can get away with a single line of Twig to set and increment the counter:

{% for block in entry.news %}
    {% if block.type == "bodyBlock" %}
        {{ block.body }}
    {% elseif block.type == "codeBlock" %}
        {% set counter = ( counter | default(0) ) + 1 %}
        <div id="accordion{{ counter }}">
            ...
        </div>
    {% endif %}
{% endfor %}

Also, I'm guessing you need the accordion elements to be chronologically numbered, but if you don't, you can use the index property of the loop variable, which is available inside the for loop:

{% for block in entry.news %}
    {% if block.type == "bodyBlock" %}
        {{ block.body }}
    {% elseif block.type == "codeBlock" %}
        <div id="accordion{{ loop.index }}">
            ...
        </div>
    {% endif %}
{% endfor %}
| improve this answer | |
  • Yup I did need them to be chronological. Thanks so much for your answer. Worked out perfectly. – julzmon Apr 9 '15 at 13:53
2

There is no simple counter++ in twig, so your solution is a good way to handle this. What are you trying to do with the counter variable? There are other functions in twig like cycle that are often useful in these situations.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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