Implementation of Variable Operation in Django Template
- 2021-10-27 08:23:24
- OfStack
Under the template in django, we know that variables are rendered {{xxx}}, but what happens when two variables are operated?
# Addition:
{{value|add:value2}}
# The result returned is value+value2 The value of, assuming that you value For 40 , value2 For 60 The expression
# The result returned is 100
# Subtraction
{{value|add -value2}}
# And the properties of addition 1 Sample, just put the first 2 Parameters become negative, and the result returned is value-value2
# Suppose value=4,value2=8, The result returned is -4
# Multiplication
{% widthratio value1 value2 value3%}
# The above code indicates that value1/value2*value3,widthratio Need 3 Parameters for multiplication Simply put the 2 Parameters equal to 1 You can
# Example: value1=10 value2=1 value3=2 The result returned is 10/1*2=20
# Division
{% widthratio value1 value2 value3%}
# The result returned is ( value1/value2 ) *value3 Simply set the value3 Equal to 1 You can divide
# Example: value1=100 value2=20 value3=1 The result returned is ( 100/20 ) *1=5
Retain two decimal places for data
<td>{{ foo.product_amount |floatformat:5 }}</td>
register = template.Library()
1 more complicated 1 more complicated operations
With add, filter, you can do even crazier things:
Calculate A ^ 2: {% widthratio A 1 A%} Calculate (A+B) ^ 2: {% widthratio Aadd: B 1 Aadd: B%} Calculation (A+B) * (C+D): {% widthratio Aadd: B 1 Cadd: D%}
Divide and preserve decimals
First define the method in the templatehelper. py file
@register.filter
def div(value, div):
'''
Decimals are converted into elements, keeping two decimal places
:param value:
:param div:
:return:
'''
return round((value / div), 2)
It can then be used in the template as follows, provided, of course, that {% load templatehelper%}:
<td>{{ foo.product_amount |div:100 }}</td>
Try a stupid method, but it doesn't work, and even if it works, it will ignore the value after the decimal point, so it is not recommended:
<td>{% widthratio foo.product_amount 100 1 as width %}{% blocktrans %}{{ width }}{% endblocktrans %}</td>#}