修改django-template if语句以忽略重复项

时间:2015-08-04 09:02:00

标签: html django django-templates django-views

如何更改for循环以忽略重复mealtype == 'Entrees'

我只需要它来创建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 %}

全李

{% 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 %}

1 个答案:

答案 0 :(得分:1)

根据评论更新以查看视图。试试这个:

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)

也是你的新模板,试试这个:

{% 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 %}