In AnQiCMS template design, we sometimes 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 calculating the total price of items, displaying dynamic percentages, or performing simple processing of certain statistical data, AnQiCMS's template engine provides intuitive and powerful arithmetic operation capabilities.

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

Template arithmetic operation

In AnQiCMS template, you can easily perform basic arithmetic operations:

  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 #}
    

    Moreover, AnQiCMS also providesaddA filter that can not only handle the addition of numbers but also flexibly handle the addition of a mix of strings and numbers. 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 the slash to divide numbers. It should be noted that the result of division may be a floating-point number, which should be especially paid attention to when precise calculation is required:

    {{ 1 / 2 }} {# 显示结果为 0.5 #}
    {{ 10 / 3 }} {# 显示结果为 3.3333333333333335 #}
    
  5. Modulus/Remainder (%)Use the percentage sign to get the remainder of the division, which is very useful when determining odd or even numbers or performing periodic calculations:

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

Operation precedence and parentheses

As with standard mathematical operations, multiplication, division, and modulus operations have higher precedence than addition and subtraction. When you need to change the order of operations, you can use parentheses to explicitly specify.()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 templates.

Combined with practical scenario applications

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

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

Firstly, by such asarchiveDetailUse tags to obtain the original price and discount rate of the product (usually stored as custom fields):

{# 假设 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 usedsetTags 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 users more effectively. AnQiCMS provides various filters to help you handle numbers and strings:

  • floatformatFilter:Used to control the number of decimal places for floating-point numbers. For example,{{ discountedPrice|floatformat:2 }}It will format the price to two decimal places, ensuring that the display is neat.
  • integerandfloatFilter:If the data type you retrieve from the background is uncertain, or you need to force it to be converted to an integer or a floating-point number for calculation, these filters will come in handy. For example,{{ "5.5"|float }}The string "5.5" will be converted to a floating-point number.
  • stringformatFilter:For more complex formatting output, you can use as you would in a programming language'sprintfFunctions similarly, embedding numbers into specific string patterns.

Summary

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


Common Questions (FAQ)

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

2. If my variable is a string type obtained from the AnQiCMS backend, can I perform arithmetic operations on it directly?This depends on the specific operation and data content.For string values that are purely numeric (e.g., "123"), in certain operation scenarios, the template engine may attempt to automatically convert them to numbers.integerorfloatThe filter explicitly converts the string type to the corresponding numeric type, for example,{{ "123.45"|float * 2 }}.

How to accumulate or calculate the average of data fetched from the background in a loop?In AnQiCMS templates, you can combineforloop andsetLabel to implement the cumulative function.For example, you can first initialize a sum variable to 0, and then add the value of the current item to the sum variable in each iteration.To calculate the average, you need to keep a record of the number of loops and then divide the total by the number.Although it is possible, it is usually recommended to handle the data in the backend controller layer for more complex statistical logic, and pass the final result to the template for display to maintain clear responsibilities of the template and performance optimization.