I’m a recent convert to jinja2 from django templates, up until now I haven’t had much trouble porting our existing templates, but now I’m tasked with converting our custom django templatetags. The one I’m having trouble with is a tag for creating a menu like structure which looks something like:
{% createmenu mainmenu %}
<!-- syntax: menuitem url-name-to-resolve <url-args> <url-kwargs> "Url Label" -->
{% menuitem main-url-name 'Home' %}
{% menuitem some-other-url-name obj.foo obj.bar 'Page2' %}
{% if some_condition %}
{% menuitem some-other-url-name obj.foo obj.bar 'Page2' %}
{% endif %}
{% menutemplate %}
<li class="
{% if menu.is_selected %}selected{% endif %}
{% if menu.is_first %}first{% endif %}
{% if menu.is_last %}last{% endif %}">
{% if menu.is_active %}
<a href="{{menu.url}}">{{menu.label}}</a>
{% else %}
<span class="inactive">{{menu.label}}</span>
{% endif %}
</li>
{% endcreatemenu %}
The behaviour of this makes setting classes on the menu items much more simple, for example, the menu knows if it’s the first or last in the list at render time, so if I surround a menu item in an if condition it may change whether it, or other nodes, are the first or last to be displayed.
Now to jinja. I’ve tried both contextfunctions, extensions, and macros but I can’t seem to get the same behaviour because I don’t know how to delay the rendering of the menu items until after I know which ones are going to be rendered. At the moment I’m completely stuck on how to continue, any help will be appreciated.
Simply use the built-in
loopvariable’sfirstandlastattriubtes: