Handling numerical calculations in AnQiCMS templates is an important aspect for the dynamic and personalized display of website data.No matter what you need to calculate the total price of goods, display discount information, or make conditional judgments based on certain numbers, AnQiCMS's powerful template engine can provide flexible support.Thanks to its Django template engine features, simple mathematical arithmetic operations can be performed directly in the template without complex code logic.

Perform expression calculation directly in the template

AnQiCMS template engine supports double curly braces{{ }}Perform various mathematical arithmetic operations internally, which is very similar to many modern template languages such as Django, Blade, and so on.You can use common operators in programming languages to perform operations such as addition, subtraction, multiplication, and division on numbers and variables.

Let's take a look at some commonly used arithmetic operations and their usage:

1. Addition (+)When you need to add two numbers together, you can simply use the plus sign. For example, if you have a product priceitem.Priceand a taxtax, and you want to display the final price including tax:

{{ item.Price + tax }}

Or, if you want to calculate the sum of two variables:

{{ quantity + bonus }}

2. Subtraction (-)Subtraction operations are also intuitive. For example, calculating the price after a discount:

{{ originalPrice - discountAmount }}

Or display the remaining stock quantity:

{{ totalStock - soldAmount }}

3. Multiplication (*)Multiplication is often used to calculate total prices or ratios. For example, to calculate the cumulative price of multiple products:

{{ item.Price * item.Quantity }}

Or to calculate a percentage:

{{ totalSales * 0.15 }} {# 计算15%的销售额 #}

4. Division (/)Division can be used to calculate an average or distribute a proportion. For example, to calculate the average number of visits:

{{ totalViews / numberOfPosts }}

It should be noted that if the divisor is zero, the system will usually return an error or a special value, and therefore, in practical applications, you may need to cooperate with conditional judgments to avoid such situations.

5. Modulo (%)The modulo operation returns the remainder when two numbers are divided. This is very useful for determining whether a number is odd or even, or for implementing interval styles in loops. For example, to determine whether a product ID is even:

{% if item.Id % 2 == 0 %}
    <div class="even-item">{{ item.Title }}</div>
{% else %}
    <div class="odd-item">{{ item.Title }}</div>
{% endif %}

Hereitem.Id % 2will return0(Ifitem.IdIs even or1(Ifitem.IdThen compare with0.

6. Comparison operationIn addition to direct arithmetic operations, you can also perform comparisons between numbers in the template, which is very common in conditional judgments. Common comparison operators include:

  • Equal (==)
  • Not equal (!=)
  • less than (<)
  • greater than (>)
  • less than or equal to (<=)
  • greater than or equal to (>=)

these comparison operators are often used with{% if %}Use tags together:

{% if product.Stock <= 5 %}
    <span style="color: red;">库存紧张!</span>
{% endif %}

{% if user.Level >= 3 %}
    <p>恭喜您成为VIP用户!</p>
{% endif %}

7. Logical OperationsLogical operators allow you to combine multiple conditions. Common logical operators include:

  • And (andor&&)
  • Or (oror||)
  • Not (notor!)

For example, check if a product is in stock and within a specific price range:

{% if product.Stock > 0 and product.Price < 100 %}
    <p>这是一个热门的实惠商品!</p>
{% endif %}

{% if user.IsAdmin or user.IsEditor %}
    <p>您有权限编辑此内容。</p>
{% endif %}

{% if not article.IsPublished %}
    <p>本文仍在草稿箱中。</p>
{% endif %}

Use variables for calculations:Variables defined in the template can directly participate in calculations, for example, fromarchiveDetailLabel gets document details,systemLabel gets system settings, etc.

{% archiveDetail productPrice with name="Price" %}
{% system shippingCost with name="ShippingCost" %}
<p>商品总价 (含运费):{{ productPrice + shippingCost }} 元</p>

Ensure the variable you get is numeric, otherwise it may cause the calculation result to be inaccurate.

Use the filter for calculation

AnQiCMS's template engine also provides a series of filters that can perform various transformations and processing on variables, including some related to numerical calculations.

1.addFilter addThe filter is specifically used to perform addition operations, and it is very convenient in chained operations.

{{ number|add:5 }} {# 将 number 的值加上 5 #}

This filter can be used for both numbers and string concatenation.

{{ "Hello "|add:"World!" }} {# 输出 "Hello World!" #}

2.divisiblebyFilterThis filter can check if a number can be divided by another number, returning a boolean value.

{% if productId|divisibleby:3 %}
    <p>这是第三组的商品。</p>
{% endif %}

3. Type conversion filter (integer,float)Sometimes the values received from a database or external input may be of string type, but you need to perform mathematical operations on them.integerandfloatFilters can convert these strings to the corresponding numeric type.

{{ "100"|integer + 20 }} {# 结果为 120 #}
{{ "3.14"|float * 2 }} {# 结果为 6.28 #}

If the conversion fails, they will return0or0.0.

4.stringformatFilterAfter completing the calculation, you may need to format the result into a specific string format, such as retaining two decimal places.stringformatThe filter can achieve this, it is similar to programming languages inprintfFunction.

{{ (totalAmount * 1.05)|stringformat:"%.2f" }} {# 计算含5%税的总额并保留两位小数 #}

Example of practical scenarios

Suppose you are building a product list page and want to display the sequence of each product