0
votes

//EDIT

I am using standard template language, not jinja. Standard template language does not support a set tag.

How can I declare a new variable using jinja?

The second line in the following code block result to an error:

{% set msg_class = "" %}

Error message:

Invalid block tag on line 13: 'set', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?

Rest of the code:

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

Using an array like in the following thread that I found, seems really ugly to me. Is it the only solution?

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

2
Are you sure you're using Jinja? That's an error from the standard Django template language. - Daniel Roseman
I thought if I use code in html templates, it's called jinja? Am I wrong? en.wikipedia.org/wiki/Jinja_(template_engine) - user2871190
Yes, you are wrong. Jinja is a separate template system, which is supported by Django but not the default. You are using the standard template language, which is well documented on the Django site, and which does not support a set tag. - Daniel Roseman
Thank you, now I know how to continue my search! - user2871190

2 Answers

2
votes

Variables in Django template language can be used like this:

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

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

1
votes

Why not simplifying it like this?

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