0

//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?

Community
  • 1
  • 1
user2871190
  • 241
  • 2
  • 5
  • 19
  • Are you sure you're using Jinja? That's an error from the standard Django template language. – Daniel Roseman Feb 03 '17 at 10:06
  • I thought if I use code in html templates, it's called jinja? Am I wrong? https://en.wikipedia.org/wiki/Jinja_(template_engine) – user2871190 Feb 03 '17 at 13:33
  • 1
    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 Feb 03 '17 at 13:41
  • Thank you, now I know how to continue my search! – user2871190 Feb 03 '17 at 13:58

2 Answers2

2

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

user2871190
  • 241
  • 2
  • 5
  • 19
  • I've been spending thirty minutes, trying to use jinja2's "set" block. I didn't realize that Django's templating was a little different than vanilla jinja2. Thank you! – nanselm2 Mar 30 '17 at 16:50
1

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] %}
jrbedard
  • 3,662
  • 5
  • 30
  • 34
  • Thanks, it's way better this way! It's not a solution for my problem tho. – user2871190 Feb 03 '17 at 13:34
  • @jrbedar in django engine there's no tag `set` sadly. Everyone thinking they actually jinja2. That was my reason why I've been searching for answer to this problem – holms Mar 10 '18 at 02:53