How to perform arithmetic operations such as addition, subtraction, multiplication, and division in the template and display the result?

Calendar 👁️ 68

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.

Related articles

How to remove leading and trailing spaces or specific characters from a string in the template using a filter?

In website content display, we often encounter situations where there are extra spaces, line breaks at the beginning and end of strings, or specific characters need to be deleted.These seemingly minor details can affect the layout and aesthetic of the page, the accuracy of data display, and even have an adverse effect on search engine optimization (SEO).AnQiCMS is a powerful template engine that provides rich filter functions, which can help us easily and elegantly handle these strings, making your content more accurate and professional.AnQiCMS's template syntax is concise and intuitive, it draws on Django

2025-11-08

How to call and display specific content or system configuration information from other sites in a multi-site management mode?

AnQiCMS's powerful multi-site management feature brings great convenience to users with multiple brands or sub-sites.It can not only help you manage different content sites uniformly, but also supports cross-site data sharing and resource integration.When you want to display content from other sites on a site, or call the system configuration information of other sites, AnQiCMS provides a simple and efficient mechanism to achieve this goal.In AnQiCMS, the core of implementing cross-site content or configuration information calls lies in the flexible use of template tags such as `siteId`

2025-11-08

How to use `Json-LD` tags to customize structured data for optimizing the rich text summary display of search engines?

When a search engine displays search results, in addition to simple titles and descriptions, it sometimes also shows images, ratings, prices, authors, and other rich information, which is called 'Rich Snippets'.These eye-catching summaries can effectively enhance the visibility of the website in search results, attract more clicks from users, and thus bring more high-quality traffic to the website.In order to obtain these rich text summaries in search engines, we need to provide search engines with a standardized data format that they can understand, which is called "structured data".Among many structured data formats

2025-11-08

How to retrieve and display the list of all related documents under the Tag detail page?

In content operation, tags (Tag) are an extremely important tool that can help us effectively organize content, improve the quality of internal links on the website, and ultimately improve the user's browsing experience and the search engine's crawling efficiency.By tagging articles, products, or other content with relevant tags, we can associate content with the same theme scattered across different categories, forming a closer knowledge network.

2025-11-08

How to customize and display a friendly shutdown notice when the website is in a closed state?

In website operation, we sometimes need to temporarily close the website, whether it is for system upgrades, data maintenance, or short-term business adjustments.It is crucial to display a friendly shutdown prompt to visitors in this case.This not only informs users of the website status, avoids unnecessary confusion, but also maintains the brand image and provides clear guidance for search engines.AnQiCMS (AnQiCMS) provides us with a flexible way to customize and display this information.### Enable website shutdown status and set basic prompts First, you need to set the website to shutdown status

2025-11-08

How to use the `archiveFilters` tag to build a dynamic document filtering feature, such as filtering by product parameters?

Using AnQiCMS's `archiveFilters` tag to build an efficient and practical dynamic filtering function In the field of content management and e-commerce, users being able to quickly and accurately find the information they need is crucial for improving website experience and conversion rates.Imagine, when users browse products or documents on your website, if they can quickly filter out the content they want based on various conditions such as color, size, brand, and even more specific parameters like processor type, memory size, etc., this will greatly enhance their user experience.Provided by AnQiCMS

2025-11-08

How can you clearly display the user's comment content, username, reply object, and posting time in the comment list?

In website content operation, the comment section is undoubtedly an important manifestation of user interaction and content depth.A well-designed, clear information presentation comment list that can significantly improve the user's browsing experience and effectively stimulate community activity.AnQiCMS's powerful template system provides us with flexible tools, allowing us to easily achieve the organization of comment content, commenters, reply objects, and posting time.### Understanding the Core Elements of Comment Lists To build a visually appealing and practical comment list, we need to ensure that several key pieces of information are presented intuitively

2025-11-08

How to automatically parse URL strings to clickable `<a>` tags in the article body or description?

In daily website content creation and management, we often need to embed some links in the article body or description, such as referencing external resources, pointing to product pages, or other related articles.If these URLs are only displayed in plain text, users will have to manually copy and paste them into the browser, which undoubtedly will greatly reduce their user experience.幸运的是,AnQiCMS 内置了非常实用的功能,可以自动将这些 URL 字符串智能识别并转换为可点击的 `a` 标签,让网站内容更加友好和便捷。This function mainly through

2025-11-08