In the template design of AnQi CMS, it is an indispensable part to create a dynamic and feature-rich website with flexible data handling and simple calculations.You may find that, in addition to displaying the content itself, some basic arithmetic operations need to be performed at the template level, such as calculating the total price of the goods, displaying the discounted price, or dynamically adjusting the style of elements based on numbers.The template engine of AnQi CMS (similar to Django syntax) provides us with intuitive and powerful arithmetic calculation capabilities, allowing these requirements to be easily implemented in the template.
Perform basic arithmetic operations directly
In AnQiCMS templates, you can perform basic arithmetic operations such as addition, subtraction, multiplication, and division directly, just like in conventional mathematical expressions.This is due to its flexible variable parsing mechanism, allowing you to directly manipulate the numeric variables available in the template.
Addition+auto-:For example, you may need to display the after-tax price of a product, or calculate the total amount of multiple products in the shopping cart. Suppose we have a variableproduct.Pricerepresents the unit price of the producttaxRaterepresents the tax rate:
{# 计算税后价格 #}
商品税后价格:{{ product.Price * (1 + taxRate) }} 元
{# 显示两个数值之和 #}
总计:{{ quantity1 + quantity2 }} 个
multiplication*and division/:Multiplication is commonly used to calculate quantity and unit price, while division can be used to calculate percentages or averages.
{# 计算多个商品的总价 #}
总价:{{ item.Price * item.Quantity }} 元
{# 计算平均分,确保至少有一个操作数是浮点数以获得小数结果 #}
平均分:{{ totalScore / studentCount|float }} 分
It should be noted that when performing division operations, if both operands are integers, the result will also be truncated to an integer (for example10 / 3You will get3)。To obtain an accurate floating-point number result, make sure at least one operand is a floating-point number (for example10.0 / 3,or use the one introduced belowfloatfilterer)。
Modulo (remainder)%:Modulo operation is very useful in templates, for example, applying different styles in a loop every few rows, or determining if one number is a multiple of another.
{# 在循环中,每三行应用一个特殊样式 #}
{% for item in list %}
<div class="item {% if forloop.Counter0 % 3 == 0 %} special-style {% endif %}">
{{ item.Title }}
</div>
{% endfor %}
Here are theforloop.Counter0Represents the index of the current loop, starting from 0.
Operation precedence:Like mathematical rules, arithmetic operations in AnQiCMS templates follow standard operation precedence (multiplication and division take precedence over addition and subtraction). If you need to change the precedence, you can use parentheses()Come to explicitly specify the order of operations.
{# 改变运算顺序的例子 #}
{{ (product.Price - discount) * item.Quantity }}
Combine logical judgment and comparison operations
Arithmetic operations are often combined with logical judgments and comparison operations to achieve more complex dynamic displays. In AnQiCMS templates, you can use==(等于), English!=(Not equal to),<(Less than),>(Greater than),<=(Less than or equal to),>=(Greater than or equal to) comparison operator. These are usually in{% if %}used inside tags.
{# 根据库存量显示不同文本 #}
{% if product.Stock <= 10 %}
<span style="color: red;">库存紧张,仅剩 {{ product.Stock }} 件!</span>
{% elif product.Stock == 0 %}
<span style="color: gray;">已售罄</span>
{% else %}
<span>库存充足</span>
{% endif %}
Using filters (Filters) for more flexible operations and formatting
AnQiCMS template engine also provides a rich set of filters (Filters), which can further extend the capabilities of arithmetic operations and help you better format the output results. The syntax for using filters is{{ 变量 | 过滤器名称 : 参数 }}.
addFilter:This filter is very intuitive, used to add two numbers or concatenate strings. It will try to handle different types intelligently.
{# 数字相加 #}
{{ current_value|add:10 }}
{# 字符串拼接 #}
{{ "安企CMS"|add:" 是您的首选" }}
floatformatFilter:When you need to precisely control the decimal places of a floating-point number,floatformatthe filter comes in handy. It can format numbers to a specified number of decimal places, often used for displaying currencies or percentages.
{# 保留两位小数 #}
{{ total_price|floatformat:2 }}
{# 保留零位小数(整数) #}
{{ percentage|floatformat:0 }}
integerandfloatFilter:Sometimes, the data you get from the content model or custom fields may be treated as a string, but you need to use it for arithmetic operations.integerandfloatThe filter can help you convert these strings to the corresponding numeric type.
{# 将字符串转换为整数进行运算 #}
{{ "50"|integer + 20 }}
{# 将字符串转换为浮点数 #}
{{ "12.5"|float * 2 }}
divisiblebyFilter:This filter is used to check if a number can be evenly divided by another number, and returns a boolean value. This is very useful for alternating styles in loops.
{# 每隔一行应用不同的背景色 #}
{% for item in items %}
<tr class="{% if forloop.Counter|divisibleby:2 %} even-row {% else %} odd-row {% endif %}">
<td>{{ item.Title }}</td>
</tr>
{% endfor %}
stringformatFilter:If you need more advanced formatting requirements,stringformatThe filter provides something similar to the Go languagefmt.Sprintffunction, which can output variables according to the specified format string.
{# 格式化为百分比 #}
{{ (progress / total)|stringformat:"%.2f%%" }}
A small reminder in practical applications
- Keep the template simple:Although the template provides powerful computing capabilities, it is still recommended to place complex computing logic in the backend controller.The main responsibility of the template is to display data, not to handle complex business logic.
- **