Django template syntax error: could not parse remainder % 2

Viewed 74

I am getting a TemplateSyntaxError: "could not parse remainder % 2 from num%2":

{% if num%2 ==0 %}
   {{"Even"}}
{% else %}
   {{"Odd"}}
{% endif %}
1 Answers

You can't use arbitrary Python expressions in Django templates. You should create a custom filter for them.

However, for your expression there is a built-in tag divisibleby. From its example:

{{ value|divisibleby:"2" }}

If value is 4, the output would be True. So the final answer looks like (untested):

{% if num|divisibleby:"2" %}
    Even
{% else %}
    Odd
{% endif %}
Related