When creating templates in AnQiCMS, we often need to perform some simple numerical calculations, such as displaying the total price of products, calculating the percentage of article views, or handling the numbering in a list.AnQiCMS supports a powerful template engine that allows direct arithmetic operations such as addition, subtraction, multiplication, and division in templates, making our content display more flexible and dynamic.

Perform direct arithmetic operations in the template

The template syntax of AnQiCMS is similar to the Django template engine, when we need to perform mathematical operations in the template, we can do so directly within double curly braces{{ }}Write an expression internally. This includes basic addition+and subtraction-and multiplication*and division/and even supports modulus operation%.

Imagine you have a product list and need to display the total price for each product (unit price multiplied by quantity). You can write the template code like this:

{% for item in productList %}
    <p>产品名称:{{ item.Name }}</p>
    <p>单价:{{ item.Price }}</p>
    <p>数量:{{ item.Quantity }}</p>
    <p>总价:{{ item.Price * item.Quantity }}</p>
{% endfor %}

Here,item.Priceanditem.QuantityThe product unit price and quantity variables passed from the backend to the template. The template engine will automatically calculate and display the result when rendering the page.item.Price * item.QuantityThe result and display it.

Similarly, if you want to perform addition or subtraction on a number, such as displaying a basic reading volume plus additional recommendations, or subtracting the number of items sold from the total inventory, you can also do so directly:

  • Addition Example:Show the actual reading volume of the article (basic views + reading volume brought by promotion)

    <p>文章阅读量:{{ archive.Views + 500 }}</p>
    
  • Subtraction Example:Calculate the remaining inventory

    <p>剩余库存:{{ product.TotalStock - product.SoldQuantity }}</p>
    
  • Division Example:Calculate a percentage (for example, the percentage of completed tasks out of the total number of tasks)

    {% set completed = 25 %}
    {% set total = 100 %}
    <p>任务完成度:{{ completed / total * 100 }}%</p>
    

    Here is something to note, ifcompletedandtotalAll are integers, in some language template engines, division may be executed by default as integer division.AnQiCMS template engine will be intelligently processed, usually giving a floating-point number result.If you need to control the number of decimal places accurately, you can use the filters introduced later.

  • Modulo example:Determine whether a number is odd or even, or implement layout logic such as a newline every N elements.

    {% for item in itemList %}
        {% if forloop.Counter % 2 == 0 %}
            <p>这是偶数项:{{ item.Title }}</p>
        {% else %}
            <p>这是奇数项:{{ item.Title }}</p>
        {% endif %}
    {% endfor %}
    

    In this example,forloop.CounterYesforA built-in counter for the current iteration number in the loop.

UseaddAddition operation using the filter.

In addition to performing operations directly in expressions, AnQiCMS's template engine also provides some convenient filters (Filters) that can process variables. Among them,addThe filter is specifically used for performing addition operations. Its usage is to add it after the variable name.|add: followed by the value to be added.

addOne of the highlights of the filter is that it can be used not only for adding numbers but also for concatenating strings.

  • Example of number addition:

    {% set basePrice = 100 %}
    {% set tax = 10 %}
    <p>含税价格:{{ basePrice|add:tax }}</p>
    
  • Example of string concatenation:

    {% set prefix = "欢迎来到" %}
    {% set siteName = "安企CMS官方网站" %}
    <p>{{ prefix|add:siteName }}</p>
    

    This will output 'Welcome to the Anqi CMS official website'. It is very useful when dynamically constructing text content.

Cautionary Notes and Useful Tips

  1. Data Type:When performing arithmetic operations, please ensure that the variables involved are of numeric type.Although template engines usually try to perform type conversions, if the variable contains non-numeric characters, it may result in inaccurate or uncomputable calculation results.
  2. Operator precedence:The arithmetic operations in the template follow the standard mathematical precedence rules, that is, multiplication and division take precedence over addition and subtraction. To avoid ambiguity and ensure that the operation sequence meets expectations, it is recommended to use parentheses() Clarify the grouping. For example:{{ (item.Price + item.ShippingCost) * item.TaxRate }}.
  3. Precision of the result:For division operations, especially when involving floating-point numbers, the result may contain a large number of decimal places. If you need to control the precision of the result or format it to a specific number of decimal places, you can consider using other filters provided by AnQiCMS, such asfloatformat(Used for floating-point formatting) orstringformat(Used for general string formatting).
  4. Debug:

With these flexible arithmetic operation capabilities, you can easily implement various dynamic data display and logical processing in the AnQiCMS template, making the website content more interactive and rich.

Common Questions and Answers (FAQ)

  1. Ask: Can I perform complex mathematical formula calculations in the template?Answer: Of course, you can. You can construct complex mathematical formulas by combining addition, subtraction, multiplication, division, parentheses, and other filters. For example, calculate(A + B) * C / DThis expression is fully supported. Just make sure the variables are of numeric type, and use parentheses properly to control the order of operations.

  2. How to ensure that my calculation result is an integer rather than a floating-point number?AnQiCMS template engine will return a floating-point number by default if the operands contain a floating-point number or the result is not an integer when performing division. If you need to force the result to be an integer, you can useintegera filter. For example{{ (total / count)|integer }}The decimal part of the result will be removed, only the integer part will be retained.

  3. Question: What will happen when the divisor is zero in the division operation of the template?Answer: When performing division operations in templates, if the divisor is zero, it usually leads to rendering errors or returning a default value (e.g., 0), depending on the specific template engine implementation and error handling mechanisms. To avoid this situation, it is recommended to useifLogical judgment label check if the divisor is zero, for example:{% if divisor != 0 %}{{ dividend / divisor }}{% else %}0{% endif %}.