0

I have a couple if/else statements that all seem to return this same parse error regardless of what page or other content exists on the page.

For all intents and purposes have dumbed it down. My actual logic makes sense, don't worry, I just want to know what of my syntax is causing this problem:

<div>
    {% if True and 10 - 1 > 5 %}
        <p>1</p>
    {% else %}
        <p>2</p>
    {% endif %}
</div>

When I do the above, I expect it to show the <p>1</p> tag but instead returns a "TemplateSyntaxError at " URL, Could not parse remainder: '-' from '-'.

djmonkey
  • 13
  • 3
  • so,its basically beacuse you can't use template if blocks like normal python if blocks.And since you are performing some maths inside it..its not able to to parse that `-` minus symbol whether its for html or what....so to do these additions and subtractions..djnago has template tags...you should probably use those – Vivek Anand May 04 '21 at 18:54

2 Answers2

0

By default, django templates does not allow math operations such as addition, subtraction, etc..

I would suggest to make the mathematical operation in your view function and render it to the template, and then use it directly Example:

def my_view(request):
    result = 10 - 1
    render(request, template, context={'my_result': result})

and then in the template you would do something like

{% if True and my_result > 5 %}
Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45
  • I understand this is what is supposed to be the best practice and is the "correct" answer. Thank you for the background information. My use case, although not adding it above, does an iteration through data I don't have access to in my controller to inject a true or false per check for said data. In reality the below helped me more, but given the question I asked I acknowledge this is the preferred. – djmonkey May 04 '21 at 19:08
0
<div>
    {% if True and 10|add:'-1' > 5 %}
        <p>1</p>
    {% else %}
        <p>2</p>
    {% endif %}
</div>

The code 10|add:'-1' means 10 + (-1)

Himaloy Mondal
  • 127
  • 2
  • 6
  • Would upvote if I could but not enough reputation. This I found the most helpful and how I ended up fixing my issue, but I do acknowledge it's the most hacky way. Anyway wanted to thank you. – djmonkey May 04 '21 at 19:09