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 %}
julzmon
  • 941
  • 2
  • 9
  • 19

2 Answers2

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 %}
Mats Mikkel Rummelhoff
  • 22,361
  • 3
  • 38
  • 69
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.

Aaron Berkowitz
  • 3,819
  • 10
  • 20