How can arithmetic operations such as addition, subtraction, multiplication, and division be performed directly in the template?

Calendar 👁️ 66

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

Related articles

How to round off floating-point numbers or round up/down in Anqi CMS template?

When using Anqi CMS for website content management, we often encounter scenarios where precise control of numbers is required, especially when it comes to floating-point numbers such as prices and statistics, where rounding up or down is particularly important.The Anqi CMS template engine provides flexible filters that can help us easily achieve these requirements.There is no direct 'ceil' or 'floor' function tag, but by reasonably utilizing existing functions, we can still achieve the purpose.### One, using `floatformat`

2025-11-08

How will the `floatformat` filter handle non-numeric input?

During the template creation process in AnQi CMS, the `floatformat` filter is a commonly used tool for handling number display, especially for floating-point number formatting.It can help us accurately control the decimal places of numbers on the page, making the data display more neat and professional.However, when the `floatformat` filter receives non-numeric input, its handling may confuse some users.Understanding this mechanism is crucial to avoiding potential display issues with page data.The main function of the `floatformat` filter is to use the parameters we specify

2025-11-08

How to force the `floatformat` filter to display a certain number of decimal places (such as 3), even if the end is zero?

In website content management, especially when it involves prices, statistics, or any scenario where it is necessary to display numbers accurately, we often need to ensure that the decimal places of the numbers are consistent.The `floatformat` filter provided by AnQi CMS is a very practical tool that helps us format floating-point numbers.However, sometimes its default behavior may be confusing, especially when the trailing zeros may quietly 'disappear', which poses a challenge for the unified display of data.Imagine you have a product priced at `12.50` yuan

2025-11-08

I want to display floating-point numbers without extra zeros, can the `floatformat` filter do that?

In AnQi CMS templates, handling the display of floating-point numbers, especially the need to remove unnecessary zeros at the end of the numbers, is a practical demand that many website operators encounter.When our product price is `12.5000` or a certain statistical number is `34.00`, these extra zeros are not only unattractive but may also confuse visitors.At this point, the `floatformat` filter built into Anqi CMS can come into play.How does the `floatformat` filter prevent extra zeros from displaying in floating-point numbers?

2025-11-08

The `add` filter supports mixing which types (integer, float, string) for addition?

In AnQiCMS template development, we often need to combine or calculate different data, especially when displaying dynamic content.Among them, the `add` filter is a very practical tool, allowing us to flexibly add values of numeric and string types.Understand how it works, which can help us build templates more efficiently and accurately.### `add` filter: Flexible addition of numbers and strings The `add` filter plays the role of 'addition' in the AnQiCMS template engine

2025-11-08

What happens when the `add` filter performs mixed addition and type conversion fails?

In the AnQi CMS template world, we often use various filters to process data, making the page display more flexible.Among them, the `add` filter is a very practical tool that allows us to add or concatenate two values.In most cases, its performance is very intuitive: when numbers are added to numbers, mathematical operations are performed;When two strings are added together, a simple text concatenation is performed.When a number is added to a string, it also cleverly converts the number to a string and concatenates it, for example, `{{ 5|add:"CMS" }}` results in `5CMS`

2025-11-08

How can you determine in a template if a number can be evenly divided by another number?

In web content display, we often encounter situations where we need to adjust the layout or style based on the divisibility of numbers, such as setting different background colors for odd and even rows of a table, or starting a new row for grouping display every fixed number of contents.In AnQi CMS template system, implementing such logical judgment is quite direct and efficient.The AnQi CMS template engine is designed to be very flexible and easy to use, it adopts a syntax structure similar to Django templates, allowing us to use simple variable references (`{{ variable_name }}`) and logical control tags (`{% if ...`)].

2025-11-08

How to get the Nth digit from the end of a number using the `get_digit` filter?

During the template creation process of Anqi CMS, we often need to handle data flexibly so that the most user-friendly information can be displayed on the front-end page.Numbers are a common form of data, and sometimes we may need to extract a specific number from a longer number.At this point, the `get_digit` filter can be put to use, which can help us easily obtain the Nth digit from the end of a number.### The core function and purpose of the `get_digit` filter The `get_digit` filter is as its name suggests

2025-11-08