skip to Main Content

I work on Django 1.11 and in my template file I’ve got this code :

{% for article in all_articles %}
    {% set color_category = 'light-blue' %}
    {% if article.category == 'SEO' %}
        {% color_category = 'light-blue' %}
    {% elif article.category == 'SEA' %}
        {% color_category = 'amber' %}
    {% elif article.category == 'Python' %}
        {% color_category = 'green' %}
    {% elif article.category == 'Django' %}
        {% color_category = 'light-green' %}
    {% else %}
        {% color_category = 'light-blue' %}
    {% endif %}
{% endfor %}

And Django returned me this error :

Exception Type: TemplateSyntaxError
Exception Value:    
Invalid block tag on line 12: 'set', expected 'empty' or 'endfor'. Did you forget to register or load this tag?

Have you got an idea ?
Ask if you need more info (like my settings file).

Thanks !

2

Answers


  1. set is not a valid tag in django. You should use with if you want to define a variable in your template.

    {% with color_category='light-blue' %}     
        Do stuff
    {% endwith %}
    

    However, it’s always better to do this kind of operation in the view in python.

    Login or Signup to reply.
  2. The solution above is correct, but with a minor mistake. There shouldn’t be a space between the variable and its value, so the correct sintaxis should be:

    {% with color_category='light-blue' %}     
        Do stuff
    {% endwith %}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search