Search code examples
pythonmysqljinja2werkzeug

Listing specific category first in Python


I have a list of categories from DB as following and it works fine + sorted by ID.

{% for category in menu_categories|sort(attribute="id"):  %}    
<div>
    {{ category.name }}
</div>
{% endfor %}

I just need one exception if category='Pizza' exist to list it first.


Solution

  • Unless I misunderstood you, this should do it:

    {% for category in menu_categories|sort(attribute="id"): %}
        {% if category.name == 'Pizza': %}
            <div> {{ category.name }} </div>
        {% endif %}
    {% endfor %}
    {% for category in menu_categories|sort(attribute="id"): %}
        {% if category.name != 'Pizza': %}
            <div> {{ category.name }} </div>
        {% endif %}
    {% endfor %}