django - 如何在 Django 模板中获得 'switch-case' 语句功能?

标签 django django-templates switch-statement case

我找到了一个 link在 Django 模板中有一个“开关”标签,但我想知道如果没有它是否可以以某种方式实现。只使用 Django 自带的东西?基本上还有其他方法可以使用多个“if”或“ifequal”语句吗?

提前感谢您提供任何提示/建议。

最佳答案

不幸的是,这对于默认的 Django 模板引擎是不可能的。你必须写一些像这样丑陋的东西来模拟一个开关。

{% if a %}
    {{ a }}
{% else %}
    {% if b %}
        {{ b }}
    {% else %}
        {% if c %}
            {{ c }}
        {% else %}
            {{ default }}
        {% endif %}
    {% endif %}
{% endif %}

或者如果只有一个 if 条件可以为真并且您不需要默认值。
{% if a %}
{{ a }}
{% endif %}
{% if b %}
{{ b }}
{% endif %}
{% if c %}
{{ c }}
{% endif %}

通常,当模板引擎不够强大而无法完成您想要的操作时,这表明代码应该移动到 Django View 中而不是模板中。例如:
# Django view
if a:
  val = a
elif b:
  val = b
elif c:
  val = c
else:
  val = default

# Template
{{ val }}

关于django - 如何在 Django 模板中获得 'switch-case' 语句功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/725771/

相关文章:

python - 使用键中的冒号解析 JSON

c++ - switch-case 语句中的变量声明

php - Switch Case 或 if else if 哪个更快更好?

python - 如何将自定义 DRF api View 映射到多个 url?

django - 使用 mongoengine 和 django 查询

python - Django 对与同一模型相关的多个字段进行注释

ios - 使用 UITableView 中单元格中的文本

python - django.core.exceptions.ImproperlyConfigured : Requested setting INSTALLED_APPS, 但设置未配置

python - 类型错误 : Cart() takes no arguments

django - 如何在渲染时向 Widget 添加属性