无效的块标记

时间:2017-02-03 01:04:21

标签: python django jinja2

//修改

我使用的是标准模板语言,而不是jinja。标准模板语言不支持set标记。

如何使用jinja声明新变量?

以下代码块中的第二行导致错误:

{% set msg_class = "" %}

错误讯息:

第13行的标记无效:'设置',预期' elif''其他'或者' endif'。您是否忘记注册或加载此标记?

其余代码:

{% if msg %}
  {% set msg_class = "" %}
  {% if status == 1 %}
    {% set msg_class = "alert alert-success" %}
  {% elif status == 3 %}
    {% set msg_class = "alert alert-danger" %}
  {% elif status == 4 %}
    {% set msg_class = "alert alert-warning" %}
  {% else %}
    {% set status = 2 %}
    {% set msg_class = "alert alert-info" %}
  {% endif %}
{% endif %}

使用我发现的以下线程中的数组,对我来说似乎真的很难看。这是唯一的解决方案吗?

Can a Jinja variable's scope extend beyond in an inner block?

2 个答案:

答案 0 :(得分:2)

Django模板语言中的变量可以这样使用:

{% with name="World" greeting="Hello" %}     
{{ greeting }} {{name}}
{% endwith %}

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#with

答案 1 :(得分:1)

为什么不这样简化?

{% set classes = ['success', 'info', 'danger', 'warning'] %}
{% if status not in [1,3,4] %}
    {% set status = 2 %}
{% endif %}
{% set msg_class = "alert alert-"+classes[status-1] %}
相关问题