Django多条件声明

时间:2018-04-02 20:32:29

标签: html django if-statement conditional jinja2

我在Django HTML模板中使用以下代码。但是,它非常重复。如何简化此代码?

它转换为,"如果您不是员工,则可以看到nav.html。如果您是员工,只有在这4页上才能看到nav.html。"

{% if not request.user.is_staff %}
    {% include ‘nav.html’ %}
    {% else %}
        {% if request.get_full_path == ‘/one/’ %}
            {% include ‘nav.html’ %}
        {% if request.get_full_path == ‘/two/’ %}
            {% include ‘nav.html’ %}
        {% if request.get_full_path == ‘/three/’ %}
            {% include ‘nav.html’ %}
        {% if request.get_full_path == ‘/four/’ %}
            {% include ‘nav.html’ %}
    {% endif %}
{% endif %}

1 个答案:

答案 0 :(得分:0)

从您的视图中,您可以发送包含要显示nav.html的路径的列表。像,

allowed_paths = ['/one/', '/two/', '/three/', '/fourth/']

在您的模板中,您可以这样做,

{% if not request.user.is_staff or request.get_full_path in allowed_paths %}
   {% include 'nav.html' %}
{% endif %}