In AnQi CMS template design, it can flexibly handle data, perform simple calculations, and is an indispensable part of creating dynamic and functional websites.You may find that, in addition to displaying the content itself, it is also necessary to complete some basic arithmetic operations at the template level, such as calculating the total price of goods, displaying the discounted price, or dynamically adjusting the style of elements based on values.The AnQi CMS template engine (similar to Django syntax) provides us with intuitive and powerful arithmetic operation capabilities, making these requirements easy to implement 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 regular mathematical expressions.This is due to its flexible variable parsing mechanism, allowing you to directly manipulate the numeric variables available in the template.

Addition+And subtraction-: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,taxRaterepresents the tax rate:

{# 计算税后价格 #}
商品税后价格:{{ product.Price * (1 + taxRate) }} 元

{# 显示两个数值之和 #}
总计:{{ quantity1 + quantity2 }} 个

Multiplication*And division/:Multiplication is often 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 you perform 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 result, ensure that at least one operand is a floating-point number (for example10.0 / 3,or use the followingfloatof a filter).

Modulo (remainder)%:Modular arithmetic is also very practical in templates, for example, to apply different styles every few lines in a loop, or to determine 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 %}

Hereforloop.Counter0Represents the current loop index, starting from 0.

Operation precedence:And the same as the mathematical rules, the arithmetic operations in AnQiCMS templates also follow the standard operation precedence (multiplication and division take precedence over addition and subtraction). If you need to change the precedence, you can use parentheses()To clearly 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 display. You can use it in AnQiCMS templates.==(equals,)!=(not equal,)<(less than,)>(greater than,)<=(less than or equal to),>=(Greater than or equal to) operator for comparison. 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 into play. 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 obtain from a content model or custom field 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 divided by another number, returning a boolean value. It 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 a language similar to Gofmt.Sprintffunctionality, which can output variables according to the specified format string.

{# 格式化为百分比 #}
{{ (progress / total)|stringformat:"%.2f%%" }}

Small reminders in practical applications

  1. Keep the template concise:Although the template provides powerful computational capabilities, it is still recommended to place complex computational logic in the backend controller.The primary responsibility of the template is to display data, rather than to handle complex business logic.
  2. **