I'm looking to ignore a value in an array, so that only three of the four children are displayed here. There are four items in the page.root
but I only want to display three of them.
<nav role="navigation">
<ul>
{% for child in page.root %}
<li>
<a href="{{ child.url }}">{{ child.title }}</a>
</li>
{% endfor %}
</ul>
</nav>
Looking through the documentation I can't find a way of limiting the for
loop.
Thanks for the help!
============
Right, I was running Stacey app that also uses Twig. Sorry for that, I should have been more specific.
With stacey, slice is a method so this solves my problem:
<nav role="navigation">
<ul>
{% for child in slice (page.root, 0,3) %}
<li>
<a href="{{ child.url }}">{{ child.title }}</a>
</li>
{% endfor %}
</ul>
</nav>
I found that here . This correctly outputs only three of the children in page.root.
"The template system is meant to express presentation not program logic." - Django documentation
So, you can use if statment,
{% for child in page.root %}
{% if child.title != 'any title' %}
<li>
<a href="{{ child.url }}">{{ child.title }}</a>
</li>
{% endif %}
{% endfor %}
The common solution for "printing only the first n items" is the slice
filter:
{% for child in page.root|slice(0, 3) %}
{# params are start and length, so that means the first 3 items #}
{% endfor %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.