Sometimes the links are in-page, sometimes they point outside. I want to be able to create an array menuitems that is passed to an include and which then generates a per-section index menu on the page.

I currently have the approach below, but I'm a little annoyed that I have to loop through projects twice because of Twig's scope. Any better ideas?

template projects.html

{% extends "_layout" %}
{% set title = 'Projects' %}
{% set projects = craft.entries.section('projects').find() %}
{% block submenu %}
    {% set menuitems = [] %}
    {% for project in projects %} {# first loop #}
        {% set menuitems = menuitems|merge([project.title]) %}
    {% endfor %}
    {% include '_includes/_submenu' %}
{% endblock %}
{% block content %}
    {% for project in projects %} {# second, unnecessary loop #}
        <a href="project_{{ project.id }}"></a>
        <h1>{{ project.title }}</h1>
    {% endfor %}
{% endblock %}

template _includes/_submenu.html

    {% for item in menuitems %}
        <li class="pageMenu">{{ item }}</li>
    {% endfor %}

  • 1
    I'm not really sure what your issue is. You have to loop twice because you want to show different data and different html. Unless you make a really nasty work around with a macro and twig perversion that returns an array with both html strings you'll have to loop twice and that's Okay. You could as well create a php function that wraps your html around each project in one loop and return them to your twig template. But I don't see that much advantage if you don't have 1000 projects you want to render – Robin Schambach Dec 30 '17 at 9:43

Your Answer

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

Browse other questions tagged or ask your own question.