Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform arithmetic operation in Jinja2

Tags:

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'
like image 374
Smriti Shrestha Avatar asked Jun 11 '19 05:06

Smriti Shrestha


People also ask

Can you do math in Jinja?

Math. Jinja allows you to calculate with values. This is rarely useful in templates but exists for completeness' sake.

How do you use arithmetic operations in Ansible?

You can use arithmetic calculations in Ansible using the Jinja syntax. This is helpful in many situations where you have stored the output of an operation, and you need to manipulate that value. All usual operation like addition, subtraction, multiplication, division, and modulo are possible.

What is arithmetic operation with example?

Arithmetic Operator is used to performing mathematical operations such as addition, subtraction, multiplication, division, modulus, etc., on the given operands. For example: 5 + 3 = 8, 5 - 3 = 2, 2 * 4 = 8, etc. are the examples of arithmetic operators.


1 Answers

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.

like image 178
was1209 Avatar answered Oct 11 '22 12:10

was1209