In AnQiCMS, templates are the foundation for displaying website content.Flexibly use templates, not only can make content display more colorful, but also can realize dynamic effects through some built-in functions.Among them, performing arithmetic operations directly in the template is a very practical feature that many users may overlook but is very useful.It allows us to handle numbers directly in the front-end template without writing additional backend code, performing operations such as addition, subtraction, multiplication, and division, thereby achieving more dynamic display effects or logical judgments.

AnQiCMS's template system borrows the syntax of Django template engine, which makes it highly flexible and intuitive in handling variables, logical control, and arithmetic operations.Below, we will discuss in detail how to perform these arithmetic operations directly in the AnQiCMS template.

Basic Arithmetic Operations

In AnQiCMS templates, you can use addition (+), subtraction(-), multiplication(*), division(/) and modulus (%Operators. These operators can be directly applied to numeric variables or constants.

  • Addition (+) and subtraction (-)They are the most basic operations, used for addition or subtraction.

    {{ 10 + 5 }} {# 输出 15 #}
    {{ 20 - 7 }} {# 输出 13 #}
    {% set itemPrice = 100 %}
    {% set discount = 15 %}
    商品的最终价格是:{{ itemPrice - discount }} {# 输出 85 #}
    
  • Multiplication (*)and division(/)Used to calculate products or quotients. It should be noted that the results of integer division and floating-point division may differ.

    {{ 4 * 6 }} {# 输出 24 #}
    {{ 10 / 3 }} {# 如果两个操作数都是整数,结果可能被截断为整数,输出 3 #}
    {{ 10 / 3.0 }} {# 至少一个操作数是浮点数时,结果会保留小数,输出 3.333333 #}
    {% set viewCount = 500 %}
    {% set factor = 0.1 %}
    阅读量得分:{{ viewCount * factor }} {# 输出 50.0 #}
    

    To ensure that the division results in a floating-point number, it is recommended to explicitly write one of the operands as a floating-point number (for example,3.0),or use the following mentionedfloatThe filter performs type conversion.

  • Modulo(%)The modulus operation returns the remainder of the division of two numbers, which is often used in templates to implement scenarios such as alternating styles of list items (odd and even rows).

    {{ 10 % 3 }} {# 输出 1 #}
    {% for item in archiveList %}
        <div class="item-{% if forloop.Counter % 2 == 0 %}even{% else %}odd{% endif %}">
            {# ... 内容 ... #}
        </div>
    {% endfor %}
    

Second, compound expressions and precedence.

When you need to mix multiple operations in an expression, you can use parentheses()to clarify the order of operations. As in the rules of mathematics, operations inside parentheses are executed first.

{{ (10 + 5) * 2 }} {# 先计算 10+5=15,再乘以2,输出 30 #}
{{ 10 + 5 * 2 }} {# 先计算 5*2=10,再加10,输出 20 #}
{% set basePrice = 50 %}
{% set taxRate = 0.1 %}
{% set shippingCost = 5 %}
总价:{{ basePrice * (1 + taxRate) + shippingCost }} {# 输出 50 * 1.1 + 5 = 55 + 5 = 60 #}

Chapter 3: Comparison and Logical Operations

In addition to arithmetic operations, AnQiCMS templates also support comparison operators and logical operators, which are very useful for conditional judgments.

  • Comparison operatorUsed to compare the size or equality of two values, returns a boolean value (trueorfalse)

    • Equal:==
    • Not equal:!=
    • Less than:<
    • Greater than:>
    • Less than or equal to:<=
    • Greater than or equal to:>=
    {% set currentNum = 10 %}
    {% if currentNum > 5 %}
        数字大于5
    {% endif %}
    {% if currentNum == 10 %}
        数字等于10
    {% endif %}
    
  • Logical operatorUsed to combine multiple conditions, returning a boolean value.

    • And:and(or)&&)
    • OR:or(or)||)
    • NOT:not(or)!)
    {% set isVip = true %}
    {% set userLevel = 3 %}
    {% if isVip and userLevel > 2 %}
        高级VIP用户
    {% endif %}
    {% if not isVip or userLevel < 1 %}
        非VIP或低等级用户
    {% endif %}
    
  • Member operator (in/not in)Used to check if a value exists in a list, array, or dictionary (map/struct), or if a key exists in a dictionary.

    {% set colorList = ["red", "green", "blue"] %}
    {% if "red" in colorList %}
        列表中包含红色
    {% endif %}
    
    
    {% set productTags = {"new": true, "sale": false} %}
    {% if "new" in productTags %} {# 检查键是否存在 #}
        新品标签存在
    {% endif %}
    

The fourth, combining actual data for calculation

The most powerful place of arithmetic operations lies in the ability to process dynamic data obtained from the built-in tags of AnQiCMS.For example, you may need to calculate a "hot score" based on the article's views or perform currency conversion based on product prices.

{# 假设 archive.Views 是文章的浏览量,archive.Id 是文章ID #}
{% set hotScore = archive.Views * 0.05 + archive.Id * 0.01 %}
<p>文章热度得分:{{ hotScore }}</p>

{# 假设 product.Price 是产品价格,需要显示加税后的价格 #}
{% set productPrice = product.Price %}
{% set taxRate = 0.08 %} {# 8%的税率 #}
<p>含税价格:{{ productPrice * (1 + taxRate) }}</p>

{# 假设有一个自定义字段 item.stock 表示库存,当库存低于10时显示“库存紧张” #}
{% if item.stock <= 10 and item.stock > 0 %}
    <span style="color: orange;">库存紧张!剩余 {{ item.stock }} 件</span>
{% elif item.stock == 0 %}
    <span style="color: red;">已售罄</span>
{% else %}
    <span>库存充足</span>
{% endif %}

Through the above examples, we can see that direct arithmetic and logical operations in the AnQiCMS template can greatly enhance the expression and dynamism of the template, reduce the dependency on backend logic, and make the front-end page more flexible and intelligent.

Practical suggestions

  • Keep it concise:Although the template supports complex calculations, it is recommended to keep the logic in the template as simple as possible. Complex calculations and business logic are still more suitable for handling on the backend.
  • Note the data type:When performing operations involving decimals such as division, make sure at least one operand is a floating-point number to avoid precision loss caused by integer division. AnQiCMS also providesfloatandintegerA filter that can perform explicit type conversion, for example{{ some_var|float * 0.1 }}.
  • Thorough testing:Any operation performed in the template, especially in a production environment, should be thoroughly tested to ensure that the results meet expectations and avoid user experience issues caused by calculation errors.

Frequently Asked Questions (FAQ)

1. Can I directly use the variable obtained through AnQiCMS tags in arithmetic operations?Absolutely, you can. For example, if you through{% archiveDetail with name="Views" %}Get the page views of the article, you can assign it to a variable and then use it directly in an expression:{% set views = archive.Views %}{{ views * 0.5 }}.An