How to perform basic arithmetic operations in the template?

Calendar 👁️ 79

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. **

Related articles

How to automatically convert URL strings in text to clickable links?

In daily content operations, we often need to mention various URLs in articles, product descriptions, or page introductions.If these URLs are displayed as plain text, users will need to manually copy and paste them to access, which undoubtedly will greatly reduce their reading experience and the interactivity of our website.How can we automatically make the URL strings in these texts clickable?In AnQi CMS, this implementation is very simple, no complex code development is required, just use its powerful template filter function to easily handle it.

2025-11-09

How to truncate long text content and add an ellipsis (...)

In the daily management of website content, we often encounter such situations: an article's summary, a product description, or a list item title, if the content is too long, it not only occupies too much page space but may also destroy the overall layout aesthetics.Especially on mobile and other small screen devices, overly long text can seriously affect user experience.How to elegantly truncate these texts and add common ellipses (...) to make the information complete and tidy, which is a very practical skill in content operation.

2025-11-09

How to safely display HTML content retrieved from a database on the frontend without escaping?

In website operation, we often need to display some content with rich formatting, such as mixed text and images on article detail pages, HTML tables on product introduction pages, or interactive codes embedded in custom pages.This content is usually stored in a database and rendered on the front-end page.However, many content management systems (including the familiar AnQiCMS) by default, for website security, will escape the HTML content retrieved from the database, resulting in the front-end displaying the original HTML code rather than the expected effect.

2025-11-09

How to format a timestamp into a readable date in the template (such as: 2023-01-01)?

<ctrl94>thought Here's a thinking process that leads to the article above: 1. **Understand the Goal:** The user wants an article about formatting timestamps in AnQiCMS templates. I need to act as

2025-11-09

How to convert a string to uppercase, lowercase, or title case?

In website content operation, the way content is presented often determines the overall impression of users on the website.Whether it is to maintain brand style consistency or to improve the readability of text, flexible case conversion of strings is a basic and important operation.AnQiCMS (AnQiCMS) understands this, and it has built-in simple and easy-to-use filters (Filters) in its powerful template engine, allowing you to easily perform string transformations such as uppercase, lowercase, and capitalization without complex programming.We will introduce in detail how to use the Anqi CMS template

2025-11-09

How to display a default value when a variable is empty?

In website operation, we often encounter such situations: a content field may not be filled in for various reasons, such as the author of the article, image description, or specific parameters of a product.If the template outputs a blank directly when displaying this content, it not only affects the aesthetics but may also confuse the user.At this time, how to display a friendly default value when a variable is empty has become a very practical skill.The AnQi CMS template system, with its flexible and powerful features, provides us with various methods to elegantly solve this problem

2025-11-09

How to get the length of a string, array, or object?

When managing website content in AnQi CMS, we often need to flexibly adjust the page display according to the number of elements in a string, array, or collection.Whether it is to judge whether the length of the article title needs to be truncated, or to count how many documents are under a certain category, or to display the number of user comments, obtaining the 'length' of this content is the key to dynamic display and logical judgment.The AnQi CMS template engine provides built-in features that are simple and efficient, helping us easily deal with these scenarios.Among them, the `length` filter is a powerful assistant for obtaining the length of strings, arrays, or key-value pairs

2025-11-09

How to format a floating-point number to a specified number of decimal places?

How to accurately control the decimal places of floating-point numbers in AnQiCMS?In website content operations, we often encounter situations where we need to display prices, statistical data, measurement results, and other floating-point numbers.However, the original floating-point numbers often have unnecessary decimal places, which not only affects the appearance but may also reduce the readability of the data.AnQiCMS fully considers this user's needs, providing flexible and powerful template filters to help us easily implement the formatting of floating-point numbers, making data display more professional and accurate.### Use `floatformat`

2025-11-09