FAQs about template writing in django: compiling djangotemplate
Django's typical MTV model recently encountered some numerical problems on the template. Compared with jsp used in java, the thymleaf template may be somewhat different and sometimes more convenient;
Django Template Addition:
{Value | add: 10} value = 5, 15 is returned.Django template subtraction:
{Value | add:-10 }}value = 5, then-5 is returned. This is a good understanding. Subtraction is to add a negative number.Django template multiplication:
The code above {% widthratio 5 1 100%} indicates: 5/1*100, 500 is returned, and widthratio requires three parameters. It uses parameter 1/parameter 2 * parameter 3, so if you want to perform multiplication, you can set parameter 2 to 1.Django performs division. The widthratio method is used here.
{% Widthratio foo. product_amount 100 1% }#} to treat The value processed by The widthratio function as a variable, use The following method: {% widthratio this_value max_value max_width as width %} {% blocktrans %} The width is: {width }}{% endblocktrans %}Retain two decimal places for Data
{{ foo.product_amount |floatformat:5 }} register = template.Library()Some complex operations
Using the add filter, you can do something crazy: Calculate A ^ 2: {% widthratio A 1 A %} and calculate (A + B) ^ 2: {% widthratio A | add: B 1 A | add: B %} calculation (A + B) * (C + D): {% widthratio A | add: B 1 C | add: D %}Divide and retain decimal places
First, define the method in templatehelper. @ register. filterdef p (value, p): ''' points are converted to RMB, and two decimal places are retained: param value: param p: return: '''return round (value/p), 2) can be used in the template as follows. Of course, the premise is {% load templatehelper % }:{ {foo. product_amount | p: 100 }}
I tried a stupid method, but it does not take effect. Even if it takes effect, it will ignore the value after the decimal point. Therefore, it is not recommended that:
{% widthratio foo.product_amount 100 1 as width %}{% blocktrans %}{{ width }}{% endblocktrans %}#}If no value exists, set the default value. | default: "" and | default_if_none: ". Who is more suitable for you?
0 will be replaced with "": {foo. remark | default: ""}. Only None will be replaced with: {foo. remark | default_if_none :""}}