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
set
is not a valid tag in django. You should usewith
if you want to define a variable in your template.However, it’s always better to do this kind of operation in the view in python.
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: