When making 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 reading, or handling the sequence numbers in a list.AnQiCMS is a powerful template engine that supports 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

AnQiCMS's template syntax is similar to the Django template engine, when we need to perform mathematical operations in the template, we can directly use double curly braces{{ }}Inside, write expressions. This includes basic addition+, subtraction-Multiplication*And division/, and even supports modulo operation%.

Imagine you have a product list and you need to display the total price of 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.QuantityThis is the product unit price and quantity variable passed from the background to the template. The template engine will automatically calculateitem.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 sold quantity from the total inventory, you can 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>
    

    Please note that ifcompletedandtotalAll are integers, in some language template engines, division may default to integer division.The AnQiCMS template engine will handle it intelligently, usually giving a floating-point result.If you need to control the decimal places accurately, you can use the filters introduced later.

  • Modulus example:Determine whether a number is odd or even, or implement line breaks every N elements and other layout logic.

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

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

UseaddThe filter performs addition operations.

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.

addA filter's highlight is that it can be used not only for adding numbers but also for concatenating strings.

  • Example of 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 practical tips

  1. Data type:When performing arithmetic operations, please ensure that the variables involved are numeric.Although template engines usually try to perform type conversions, if the variable contains non-numeric characters, it may lead to inaccurate or uncomputable calculation results.
  2. Operator precedence:The arithmetic operations in the template follow standard mathematical precedence rules, that is, multiplication and division take precedence over addition and subtraction. To avoid ambiguity and ensure that the order of operations is as expected, it is recommended to use parentheses()To clearly group. For example:{{ (item.Price + item.ShippingCost) * item.TaxRate }}.
  3. Accuracy 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 asfloatformatOr used for floating-point number formattingstringformatOr used for general string formatting.
  4. Debug:If the calculation result does not meet expectations, you can try to output each variable involved in the calculation separately and check if their values are correct.At the same time, check the HTML source code of the template to ensure there are no issues due to unclosed tags or other syntax errors.

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.

Frequently Asked Questions (FAQ)

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

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

  3. Question: What will happen when division by zero occurs in the template?Answer: When performing division operations in a template, if the divisor is zero, it usually leads to a template rendering error or returning a default value (such as 0), depending on the specific template engine implementation and error handling mechanism. To avoid this situation, it is recommended to useifCheck if the divisor is zero, for example:{% if divisor != 0 %}{{ dividend / divisor }}{% else %}0{% endif %}.