In AnQiCMS template design, sometimes we need to perform arithmetic operations such as addition, subtraction, multiplication, and division on the numbers displayed on the page to present data more flexibly.Whether it is to calculate the total price of goods, display dynamic percentages, or perform simple processing of certain statistical data, the template engine of AnQiCMS provides intuitive and powerful arithmetic calculation capabilities.

AnQiCMS's template engine borrowed the syntax style similar to Django templates, which allows us to directly output variables in template files (using{{ }}Use and logical control (with){% %}It is worth mentioning that in terms of numerical calculations, it supports expressions commonly used in mathematics, making calculations in templates very direct and convenient.

Operations of arithmetic in the template

In AnQiCMS template, you can easily perform basic arithmetic:

  1. Addition (+)You can directly use the plus sign to add numbers or variables that can be converted to numbers. For example, if you want to add two numbers and display the result:

    {{ 10 + 20 }} {# 显示结果为 30 #}
    

    In addition, AnQiCMS also providesaddA filter that can not only handle the addition of numbers, but also flexibly handle the addition of strings and numbers mixed together. When you need to process data from different sources (which may be some strings and some numbers),addThe filter will be very useful.

    {{ 5|add:2 }} {# 显示结果为 7 #}
    {{ "安企"|add:"CMS" }} {# 显示结果为 安企CMS #}
    
  2. Subtraction (-)Subtract numbers using the minus sign:

    {{ 100 - 10 }} {# 显示结果为 90 #}
    
  3. Multiplication (*)Multiply numbers using the asterisk:

    {{ 2 * 5 }} {# 显示结果为 10 #}
    
  4. Division (/)Use a slash to divide numbers. It should be noted that the result of division may be a floating-point number, which should be paid special attention to when precise calculation is required:

    {{ 1 / 2 }} {# 显示结果为 0.5 #}
    {{ 10 / 3 }} {# 显示结果为 3.3333333333333335 #}
    
  5. Modulo/remainder (%)Using the percent sign to get the remainder of division is very useful when determining parity or performing periodic calculations:

    {{ 10 % 3 }} {# 显示结果为 1 #}
    

Operation precedence and parentheses

As with standard mathematical operations, multiplication, division, and modulo operations have higher precedence than addition and subtraction. You can use parentheses to change the order of operations.()specify it explicitly. For example:

{{ 10 + 24 / 6 / 2 }} {# 结果为 12,先进行除法 #}
{{ (10 + 24) / 6 / 2 }} {# 结果为 2.8333...,先进行括号内的加法 #}

The AnQiCMS template engine even supports more complex expressions, which provides great flexibility for dynamic calculations in the template.

Combine with actual application scenarios

In the operation of actual websites, we often obtain various data from the AnQiCMS backend, such as the number of views of articles, inventory of goods, product prices, and so on.You can directly introduce these variables into the template for arithmetic operations.

Assuming you need to display the original price, discount rate, and calculate the discounted price and the amount saved for the user on the product detail page. You can do it like this:

First, by such asarchiveDetailThe tag to get the original price and discount rate of the product (usually stored as a custom field):

{# 假设 originalPrice 和 discountRate 是从后台获取的变量 #}
{% set originalPrice = 199.99 %}
{% set discountRate = 0.8 %} {# 假设后台存储为0.8表示八折 #}

{% set discountedPrice = originalPrice * discountRate %}
{% set savedAmount = originalPrice - discountedPrice %}

<p>商品原价:<span class="original-price">¥{{ originalPrice }}</span></p>
<p>折扣价:<span class="discounted-price">¥{{ discountedPrice|floatformat:2 }}</span></p>
<p>为您节省:<span class="saved-amount">¥{{ savedAmount|floatformat:2 }}</span></p>

In this example, we used:setTags define temporary variables in the template, which helps organize and simplify complex calculation expressions.

Use filters to format the results.

The calculation result may require further formatting to be displayed to the user. AnQiCMS provides various filters to help you process numbers and strings:

  • floatformatFilter:Used to control the decimal places of floating-point numbers. For example,{{ discountedPrice|floatformat:2 }}Will format the price to two decimal places, ensuring neat display.
  • integerandfloatFilter:If you are unsure of the data type you are getting from the backend, or need to force it to an integer or float for calculation, these filters will come in handy. For example,{{ "5.5"|float }}Converts the string '5.5' to a floating-point number.
  • stringformatFilter:Used for more complex formatting output, you can use it like programming languages.printfFunctions the same, embed numbers into a specific string pattern.

Summary

AnQiCMS template engine provides flexible and powerful arithmetic calculation capabilities, allowing you to directly process numeric data in front-end templates, achieving more dynamic and expressive content display.By using direct mathematical symbols and practical filters, you can easily meet various computational needs, enhancing the user experience and content operation efficiency of the website.


Frequently Asked Questions (FAQ)

1. Can I directly use JavaScript for complex mathematical calculations in the AnQiCMS template?The AnQiCMS template engine is mainly used for server-side rendering, and it is recommended to use its built-in arithmetic operations and filters to process numbers within the template.Although you can embed JavaScript code in the template, it is not recommended to write complex JavaScript in the template logic for core data calculations during page loading, due to security and performance considerations.Complex frontend interaction or calculation, it is best to prepare the data in advance and then process it through JavaScript on the browser side.

Can I directly perform numerical operations on a variable that is a string type from the AnQiCMS backend?This depends on the specific operation and data content. In certain operation scenarios, the template engine may try to automatically convert it to a number for pure numeric strings (such as "123").However, to ensure the accuracy of calculations and avoid potential errors, it is recommended to useintegerorfloatThe filter explicitly converts the string type to the corresponding numeric type, for example{{ "123.45"|float * 2 }}.

3. How to accumulate or calculate the average of data obtained from the background in a loop?In the AnQiCMS template, you can combineforloop andsetThe tag can be used to implement the accumulation function. For example, you can first initialize a total variable to 0, and then add the value of the current item to the total variable in each loop.To calculate the average, you need to record the number of loops and then divide the sum by the number of times.It can be implemented, but for more complex statistical logic, it is usually recommended to process the data in the backend controller layer, and pass the final result to the template for display to maintain the clarity of the template's responsibilities and performance optimization.