django

Display markup conditionally using the length of a list in Django templates

By using the length filter within an if statement, you can conditionally show markup in a Django template.

example: Add the class two-columns to the submenu div if there are more than 10 menu_item.children items.

<div class="submenu {% if menu_item.children|length > 10 %}two-columns{% endif %}">
    <!-- content -->
</div>

if there are more than 10 items, it will return

<div class="submenu two-columns">  
    <!-- content -->
</div>

otherwise, it will return

<div class="submenu">  
    <!-- content -->
</div>

more Django posts

more HTML posts