Victor Yee
Victor Yee

Reputation: 151

Amend django-template if statement to ignore duplicates

How do I change the for loop to ignore duplicates mealtype == 'Entrees'

I only need it to create 1 <a href>

{% for menu in menus %}
            {% if menu.mealtype == 'Entrees' %}
            <li role="presentation">
                <a href="#tab1" aria-controls="tab1" role="tab" data-toggle="tab">Entrees</a>
            </li>
            {% endif %}
{% endfor %}

full li

{% for menu in menus %}
    {% if menu.show_presentation %}
    <li role="presentation">
        <a href="#tab1" aria-controls="tab1" role="tab" data-toggle="tab">Entrees</a>
    </li>
    {% endif %}

    {% if menu.show_presentation %}
    <li role="presentation">
        <a href="#tab2" aria-controls="tab2" role="tab" data-toggle="tab">Sides</a>
    </li>
    {% endif %}

    {% if menu.show_presentation %}
    <li role="presentation">
        <a href="#tab3" aria-controls="tab3" role="tab" data-toggle="tab">Mains</a>
    </li>
    {% endif %}

    {% if menu.show_presentation %}
    <li role="presentation">
        <a href="#tab4" aria-controls="tab4" role="tab" data-toggle="tab">Drinks</a>
    </li>
    {% endif %}

    {% if menu.show_presentation %}
    <li role="presentation">
        <a href="#tab5" aria-controls="tab2" role="tab" data-toggle="tab">Desserts</a>
    </li>
    {% endif %}

    {% if menu.show_presentation %}
    <li role="presentation">
        <a href="#tab6" aria-controls="tab3" role="tab" data-toggle="tab">Specials</a>
    </li>
    {% endif %}

    {% if menu.show_presentation %}
    <li role="presentation">
        <a href="#tab7" aria-controls="tab4" role="tab" data-toggle="tab">Others</a>
    </li>
    {% endif %}
{% endfor %}

Upvotes: 0

Views: 453

Answers (1)

Bogdan Goie
Bogdan Goie

Reputation: 1307

Update for view based on comments. Try this:

show_presentation_list = []
menus_presentation = []

for menu in menus:
    if menu.mealtype and menu.mealtype not in show_presentation_list:
        show_presentation_list.append(menu.mealtype)
        menus_presentation.append(menu)

Also your new template, try this:

{% for menu in menus_presentation %}
    <li role="presentation">
            <a href="#tab{{forloop.counter}}" aria-controls="tab{{forloop.counter}}" role="tab" data-toggle="tab">{{menu.mealtype}}</a> 
    </li>
{% endfor %}

Upvotes: 1

Related Questions