Twig / Grav modular get index

453 views Asked by At

Can i get the index from the outer loop or pass it in somehow to an inner module?

list.html.twig

<ul>
    {% for module in page.collection %}
        <li>
            {{ module.content }}
        </li>
    {% endfor %}
</ul>

service.html.twig

<h2>{{ loop.index }} </h2>

enter image description here

Edit

I still can't figure this out. Is it possible to get the index of current module inside its twig template based on the index at which it appears in its order? So Communications strategy should be index 2 ... or 1 if 0 base.

1

There are 1 answers

0
Mike Mellor On BEST ANSWER

Finally figured out a workaround.

You can include a modular like this instead

<ul>
    {% for module in page.collection %}
        <li>
            {% include module.template ~ '.html.twig' with {page: module} %}
        </li>
    {% endfor %}
</ul>

It probably has a slight performance hit doing it this way as i believe you're rendering the partial for a second time but it gives you complete access to the outer scope.

Edit

This functionality was actually missing from the page object so i added it in and it can be used as of v1.3.3

https://learn.getgrav.org/themes/theme-vars#currentposition