In AnQiCMS template design, performing preliminary arithmetic operations on user input data is a key link in achieving dynamic content display and interactive logic.AnQiCMS's powerful template engine, drawing on the characteristics of Go language and Django templates, provides developers with flexible and easy-to-understand arithmetic calculation capabilities, allowing you to handle various numerical logic in front-end templates without writing complex backend code.
Core arithmetic operations in the template
AnQiCMS template supports direct use within double curly braces{{ }}Perform basic arithmetic operations.Whether it is simple addition, subtraction, multiplication, and division, or a slightly more complex modulo operation, it can be completed directly here.This greatly simplifies data processing at the template level.
You can directly use common mathematical operators:
- Addition(
+) - Subtraction(
-) - Multiplication(
*) - Division(
/) - Modulo(
%) - Power operation(
^)
For example, if you have a product with a template variablearchive.PriceRepresents the price,archive.StockIndicates the inventory quantity, to calculate the total inventory value, you can write it directly:
产品的总库存价值:{{ archive.Price * archive.Stock }} 元
A more complex expression, such as calculating the price of a product after a 70% discount and adding a fixed shipping fee:
打折后含运费价格:{{ archive.Price * 0.7 + 10 }} 元
Even priority operations within parentheses can be performed, for example, calculating the remainder of a number divided by 2:
{{ (archive.Stock + 7) % 7 }}
These operations support integers and floating-point numbers, the template engine will automatically handle data type conversion, making your calculation process smoother.
Use filters for auxiliary calculation and processing.
In addition to direct operators, AnQiCMS template filters also provide great convenience for data processing, especially in data type conversion and formatted output.
addFilter: General AdditionaddThe filter can not only perform addition of numbers but also handle string concatenation.It will automatically try to convert the parameter to a number for addition, and if it fails, it will perform string concatenation.item.Quantityanditem.BonusQuantity) Add:总数量:{{ item.Quantity | add: item.BonusQuantity }}If a field's value is a string,
addThe filter can also handle flexibly:文本和数字拼接:{{ "库存总量:" | add: archive.Stock }}integerandfloatFilter: Data Type ConversionData read from the database or data entered by the user in the background, which is sometimes stored as a string type. It is very important to ensure that they are numeric types before performing arithmetic operations.integerandfloatThe filter can convert a string to an integer or a floating-point number. For example, ifarchive.DiscountRatestored as “0.8” (a string), and you want to calculate the discounted price:当前折扣价格:{{ archive.Price * (archive.DiscountRate | float) }}If
archive.CountIt could be “5”, make sure it is an integer:乘以五:{{ (archive.Count | integer) * 5 }}stringformatFilter: formatted outputWhen displaying calculation results, especially when involving amounts or percentages, precise formatting is often required.stringformatThe filter can help you output numbers according to the formatting rules of the Go language. For example, keep the total price calculated to two decimal places:总计金额:{{ total_price | stringformat:"%.2f" }}divisiblebyFilter: Check for divisibilityThis filter can determine whether a number can be divided by another number and return a boolean value. It is often used in loops, such as implementing alternating row color effects:{% if forloop.Counter | divisibleby:2 %} <li class="even-row">...</li> {% else %} <li class="odd-row">...</li> {% endif %}
Combine variable assignment with logical control
To make the calculation process clearer, or if the calculation result needs to be used in multiple places later, we can combine{% set %}labels to define temporary variables. At the same time,{% if %}Tags can execute different logic based on the calculation results.
Assuming you need to judge whether the total price of the goods meets the free shipping condition:
{% set subtotal_price = archive.Price * archive.Quantity %}
{% set shipping_cost = 15 %} {# 假设固定运费 #}
{% if subtotal_price >= 200 %}
{% set final_price = subtotal_price %}
<p>恭喜您,订单满200元,免运费!</p>
{% else %}
{% set final_price = subtotal_price | add: shipping_cost %}
<p>订单未满200元,需支付运费:{{ shipping_cost }} 元。</p>
{% endif %}
<p>订单总计:{{ final_price | stringformat:"%.2f" }} 元</p>
This example demonstrates how to retrieve data, perform arithmetic calculations, store results in variables, and make conditional judgments based on variable values, ultimately outputting formatted results.
Summary
The arithmetic operation function in AnQiCMS templates, combined with its flexible filters and variable assignment mechanism, provides strong support for the dynamic processing of front-end content.Whether it is a simple numerical calculation or logical judgment based on the calculation result, it can be efficiently completed at the template level.This makes it easier to create a website that dynamically displays prices, quantities, discounts, or shows different content based on numerical conditions.
Frequently Asked Questions (FAQ)
Ask: Can arithmetic operations be performed directly on numeric data stored as strings (e.g., “100”)?Answer: It is not recommended to perform arithmetic operations directly. Although in some cases the template engine may try to automatically convert, it is strongly recommended to use
integerThe filter converts it to an integer or usesfloatThe filter converts it to a floating-point number and then performs calculations. For example:{{ "100" | integer * 5 }}.Ask: Is AnQiCMS template layer suitable for handling very complex mathematical calculations?Answer: AnQiCMS template layer is mainly used for preliminary, display-level arithmetic operations and logical judgments.For scenarios involving a large amount of data processing, complex business rules, or high-precision calculations, we recommend placing this logic in the Go language backend and then passing the final result to the template for display.This helps maintain the clarity, maintainability, and ensure the performance and accuracy of the calculation.
Ask: How can you store a calculation result in a template for reuse in multiple places?Answer: You can use
{% set %}tags to define a temporary variable, and assign the calculation result to it. For example:{% set total_amount = item.Price * item.Quantity %}. Thistotal_amountThe variable can be used in the subsequent part of the current template