htmlwebblogsnunjucks

How to stop a for loop that has "include tags" in certain item in Nunjucks?


I have this code on my blog site but I want the loop to stop in, for example, the second item/article or third

<div class="container mar2ritlft">
    <div class="content3col">

        {%- for article in collections.article | reverse -%}
        {% include 'article-post.njk' %}
        {%- endfor -%}

    </div>
</div>

Ps: the "collections.article" is blogs that have "article" tag in the metaData


Solution

  • You may want to reconsider your approach on looping through multiple articles by allowing the index of your loop to have a relationship to the actual articles. If so, you should be able to pull off the following...

        {%- for articleTitle in collections.article | reverse -%}
          {% if loop.index > 2 %}
            {{articleTitle}} {# a collection of blog titles???#} 
            {% include "articles/article-post" + loop.index + ".njk" %}
          {% endif %}
        {%- endfor -%}
    

    In your articles/ directory, you would have something like...