【问题标题】:Django Multi-Conditional StatementDjango 多条件语句
【发布时间】:2018-09-12 02:09:47
【问题描述】:

我有以下代码在 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 %}

【问题讨论】:

  • 到目前为止你有没有尝试过?您可以检查变量是否在某个列表中。

标签: html django if-statement conditional jinja2


【解决方案1】:

从您的角度来看,您可以发送一个列表,其中包含要显示 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 %}

【讨论】:

  • 完美解决方案!
  • @user7358991 也很简单 ;)
猜你喜欢
  • 2019-10-05
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 2016-06-03
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多