Under the powerful system of AnQi CMS, content operation is far more than just a pile of text and images.For modern websites, especially for e-commerce, data display, or scenarios requiring dynamic calculations, the ability to perform numerical calculations directly in templates is particularly important.It makes our pages no longer static display boards, but smart interfaces that can respond in real-time based on data.Today, let's delve into how AnQiCMS templates cleverly handle arithmetic operations such as addition, subtraction, multiplication, and division, turning technical details into practical tools for your website operations.

AnQiCMS uses a syntax similar to the Django template engine, which is very quick for peers familiar with web development. In the template, we are accustomed to using double curly braces{{ 变量 }}Output data, while using single curly braces and percent signs{% 标签 %}To control logic and execute specific operations. It is through these flexible tags and built-in filters that AnQiCMS has opened the door for us to perform numerical calculations at the template level.

Core: Direct application of arithmetic operation tags

AnQiCMS's template engine supports direct use of standard arithmetic operators in variable output expressions, making basic numeric calculations intuitive and convenient. We can use the plus sign (+)、minus(-)、multiplication(*)、division(/)、modulus(%)as well as exponentiation(^To handle numbers.

Whether it is an integer or a floating-point number, the template engine can intelligently recognize and perform correct calculations.For example, you may need to calculate the total tax-inclusive price of goods, display a percentage progress, or make simple logical judgments based on inventory quantity.

Let's see some actual examples:

  • Addition and subtraction:Assuming you have a product, you need to display its original price and discounted price, or calculate the sum of two numbers.

    {% set originalPrice = 100 %}
    {% set discountAmount = 20 %}
    <p>原价:{{ originalPrice }}元</p>
    <p>折扣价:{{ originalPrice - discountAmount }}元</p> {# 简单减法 #}
    
    
    {% set quantity = 5 %}
    {% set shippingFee = 10 %}
    <p>总费用:{{ originalPrice * quantity - discountAmount * quantity + shippingFee }}元</p> {# 复杂组合计算 #}
    

    Here, we not only performed simple subtraction, but also demonstrated how to mix multiplication, subtraction, and addition in the same expression to calculate a more complex total cost, just like we list equations on paper.

  • Multiplication and division:Calculating the total price of goods, unit price, or calculating the average value in data reports is a common occurrence in e-commerce scenarios.

    {% set unitPrice = 50.50 %}
    {% set itemsCount = 3 %}
    {% set taxRate = 0.13 %}
    <p>商品小计:{{ unitPrice * itemsCount }}元</p> {# 乘法运算 #}
    <p>含税总价:{{ unitPrice * itemsCount * (1 + taxRate) | floatformat:2 }}元</p> {# 乘法与加法的组合,并使用floatformat过滤器保留两位小数 #}
    
    
    {% set totalSales = 12500 %}
    {% set totalOrders = 250 %}
    <p>平均订单价值:{{ totalSales / totalOrders | floatformat:2 }}元</p> {# 除法运算,保留两位小数 #}
    
  • Modulus operation (%) and exponentiation (^):The modulus operation is very useful when you need to output a specific style in a loop (such as adding a special separator every 3 items), or when handling the remaining item count in pagination.Exponents can be used for more advanced mathematical calculations.

    {% set currentPage = 3 %}
    {% set itemsPerPage = 10 %}
    {% set totalItems = 53 %}
    <p>当前页面显示的起始索引:{{ (currentPage - 1) * itemsPerPage }}</p>
    <p>当前页面剩余商品数量(如果不足一页):{{ totalItems % itemsPerPage }}</p> {# 取模运算,得到余数 #}
    
    
    {% set base = 2 %}
    {% set exponent = 3 %}
    <p>2的3次方:{{ base ^ exponent }}</p> {# 幂运算 #}
    

It is worth noting that the AnQiCMS template engine follows standard operator precedence rules, and you can do so as in other programming languages by using parentheses()Specify the order of operations clearly.

Use cleverlyaddFilter: Flexible addition of numbers and strings

In addition to direct+Operators, AnQiCMS also provides a namedaddThe powerful filter (Filter), used for processing the addition of numbers or strings.It is particularly special because it intelligently tries to perform numerical addition, and if the operands cannot be converted to numbers, it will resort to concatenating them as strings.

Usage:{{ obj|add:obj2 }}

For example:

{% set num1 = 10 %}
{% set num2 = 5 %}
{% set text1 = "总金额:" %}
{% set text2 = "元" %}

<p>数字相加:{{ num1|add:num2 }}</p> {# 结果:15 #}
<p>数字与字符串相加:{{ text1|add:num1 }}</p> {# 结果:总金额:10 #}
<p>字符串拼接:{{ text1|add:text2 }}</p> {# 结果:总金额:元 #}
<p>混合类型:{{ num1|add:"5.5" }}</p> {# 结果:15.5,尝试转换为浮点数并相加 #}
<p>更复杂的混合:{{ "当前库存"|add:num1|add:"个" }}</p> {# 结果:当前库存10个 #}

addThe filter is very convenient when processing dynamic text and numeric combinations, you don't have to worry about manual type conversion.

Variable assignment and intermediate results: making complex calculations clearer

When dealing with multi-step calculations or when the result needs to be reused, it is a good practice to store intermediate values in variables. AnQiCMS provides{% set %}and{% with %}Using tags to implement variable assignment greatly enhances the readability and maintainability of the template.

  • {% set %}:Used to declare and assign variables within the current template scope.

    {% set subtotal = product.price * product.quantity %}
    {% set tax = subtotal * 0.08 %}
    {% set grandTotal = subtotal + tax + shipping.cost %}
    
    
    <p>商品小计:{{ subtotal | floatformat:2 }}元</p>
    <p>税费:{{ tax | floatformat:2 }}元</p>
    <p>总计:{{ grandTotal | floatformat:2 }}元</p>
    
  • {% with %}:It is usually used to define a local variable within a code block or to pass variables to an included (include) template.

    {% with totalSales = 15000, monthlyGoal = 20000 %}
        <p>本月销售额:{{ totalSales }}元</p>
        <p>距离目标还差:{{ monthlyGoal - totalSales }}元</p>
    {% endwith %}
    

    In this way, you can decompose complex calculations into smaller, easier-to-manage parts, making the template logic clear at a glance.

Application scenarios and precautions

The numeric calculation capability of AnQiCMS templates provides infinite possibilities for your website operation:

  1. E-commerce platform:Real-time calculation of the total shopping cart price, order discount, shipping fee, or display different prices based on user level.
  2. Data reports and dashboards:Display sales growth rate, user activity percentage, inventory surplus/shortage and other key indicators.
  3. Content ranking and recommendation: Calculate weights based on the reading volume, likes, and other data for dynamic sorting.
  4. Interactive elements:Such as survey scores, voting result statistics, and so on.

However, there are also some points to note during use:

  • The risk of division by zero:When performing division operations, be sure to consider the possibility that the divisor may be zero. If the divisor is zero, the template engine may throw an error or return an uncertain result. You can use{% if %}Tag for conditional judgment, avoid such errors: “`twig {% set divisor = item.count %} {% if divisor !