Smriti Shrestha
Smriti Shrestha

Reputation: 139

Perform arithmetic operation in Jinja2

I want to find the difference between two different values. But, I am getting a Jinja2 error. I am not sure about how to find the difference in this template.

I tried using - operator but this did not work. So, I used sub to find the difference between actual and predicted score.

 {% for e in question.essays %}
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title">{{loop.index}}</h3>
        </div>
        <div class="panel-body">
            <div class="actual-score">Actual score: {% if e.actual_score %} {{e.actual_score|round(1)}}/5{% endif %}</div>
            <div class="predicted-score">Predicted score: {% if e.predicted_score %}{{e.predicted_score|round(1)}}/5{% endif %}</div>
            <p class="essay-text">Text: {{e.text}}</p>
        <div class="diff">Difference: {{ e.actual_score|sub(e.predicted_score)}} </div>

        </div>

I am getting this error:

TemplateAssertionError: no filter named 'sub'

Upvotes: 7

Views: 33162

Answers (1)

was1209
was1209

Reputation: 288

According to the Jinja2 documentation, using - should work pretty fine. Also from my end, it is working just fine. Mind posting the error message you get when using the operator. I also cannot find the sub tag in the documentation for Jinja2.

Therefore, as Amazing Things Around You has said, I think this should work:

{{ e.actual_score - e.predicted_score }} 

Just a side note, the only other template tag I have found that does arithmetic operations close to that is Django's add tag, which also does not do subtraction.

Upvotes: 6

Related Questions