Search code examples
apostropheapostrophe-cmsnunjucks

How to load index from for loop inside widget to use it in if condition


I have widget load pieces and I set for loop to load single item inside this widget and I want inside for loop to set index for each element to take advantage from it to make if condition, How I can do that?

here is my for loop inside widget: {% for piece in data.widget._pieces %}

and I tried to set index like this but it didn't work: {% set index = data.piece.__dotPath | replace(".", "-") %}


Solution

  • Using nunjucks's built-in loop object, you can conditionally check what index your loop is at and choose to do something special like

    {% for piece in data.widget._pieces %}
        {% if loop.index ===  1 %}
            ... something special
        {% else %}
            ... something normal
        {% endif %}
    {% endfor %}