How to perform basic arithmetic operations on numbers in templates and display the results?

Calendar 👁️ 80

In website operations, we often need to dynamically display some numeric information, such as the total price of products, the percentage of article reading, the discounted price, and so on.The template system provided by AnqiCMS is powerful, it uses a syntax similar to Django template engine, allowing us to easily meet these requirements in content display, perform basic arithmetic operations directly in the template, and display the results.

Master basic arithmetic operations in the template

In the Anqi CMS template, the most direct way is to write arithmetic expressions in double curly braces{{ }}This is very similar to the calculator function we use in daily life, supporting addition+, subtraction-Multiplication*Division/as well as modulus (remainder)%and basic operations.

Imagine that you might want to display the result of adding two numbers on a page, or calculate a percentage of a number. These operations can be performed directly in the template, for example:

{# 简单的加法 #}
<p>25 + 10 的结果是: {{ 25 + 10 }}</p>

{# 减法运算 #}
<p>50 - 15 的结果是: {{ 50 - 15 }}</p>

{# 乘法运算 #}
<p>5 * 8 的结果是: {{ 5 * 8 }}</p>

{# 除法运算,这里会得到浮点数结果 #}
<p>10 除以 3 的结果是: {{ 10 / 3 }}</p>

{# 整数除法,会得到整数部分 #}
<p>10 整除 3 的结果是: {{ 10 // 3 }}</p>

{# 取模运算,得到余数 #}
<p>10 除以 3 的余数是: {{ 10 % 3 }}</p>

In actual display,{{ 10 / 3 }}It will output.3.3333333333333335while{{ 10 // 3 }}it will output3This means that when performing division, if you want to get an exact floating-point result, you usually use/and if you only need the integer part, you can use//Or through subsequent filters to be processed.

These expressions can also include parentheses to clarify the order of operations, just like you learned in math class. For example, calculate(5 + 3) * 2The result is:

<p>(5 + 3) * 2 的结果是: {{ (5 + 3) * 2 }}</p>

Integrate website data into arithmetic operations

The mere operation of fixed numbers is often not enough to meet our needs, the charm of a website lies in the dynamism of its content.AnQi CMS allows us to retrieve various data from the background and use the numeric values in the template calculations.

Assuming we have a product details page, the unit price of the product isarchive.Price(Through the document details tagarchiveDetailGet the field, and we want to calculate the total price of buying 3 items. We can do this:

{# 假设 archive.Price 是一个数字,比如 29.99 #}
{% archiveDetail productPrice with name="Price" %}
<p>商品单价:¥{{ productPrice }}</p>
<p>购买 3 件商品的总价:¥{{ productPrice * 3 }}</p>

Or if your document model has a custom numeric field, such asStock(Inventory), if you want to display how much inventory is left in percentage, you can calculate it like this:

{# 假设 archive.TotalStock 是一个固定值,archive.CurrentStock 是当前库存 #}
{% archiveDetail totalStockValue with name="TotalStock" %}
{% archiveDetail currentStockValue with name="CurrentStock" %}

{% if totalStockValue > 0 %}
  {% set remainingPercentage = (currentStockValue / totalStockValue) * 100 %}
  <p>总库存:{{ totalStockValue }}</p>
  <p>当前库存:{{ currentStockValue }}</p>
  <p>库存剩余百分比:{{ remainingPercentage|floatformat:2 }}%</p> {# 使用 floatformat 过滤器保留两位小数 #}
{% else %}
  <p>库存信息不可用或总库存为零。</p>
{% endif %}

Here we introduced one{% set %}tag to define a temporary variableremainingPercentageand usedfloatformat:2a filter to keep the result to two decimal places, making the display more tidy.

Using the filter for more flexible calculations

The AnQi CMS template system also provides some practical filters (Filters) that can help us process and calculate data. Filters are added by adding a vertical bar after the variable name.|And use the filter name.

Among them,addThe filter is very suitable for performing simple addition operations. It can not only be used for adding numbers, but also cleverly handle the mixed addition of numbers and strings (if possible, it will try to convert the types, otherwise, it will ignore the parts that cannot be converted).

{# 使用 add 过滤器进行加法 #}
<p>5 加 2 的结果是: {{ 5|add:2 }}</p>

{# 变量与数字相加 #}
{% set baseNum = 10 %}
<p>10 加 7 的结果是: {{ baseNum|add:7 }}</p>

{# 字符串与数字相加(会尝试拼接,如“安企” + 2 = “安企2”) #}
<p>“安企”与 2 相加: {{ "安企"|add:2 }}</p>

Sometimes, the value obtained from the custom field at the back may be treated as a string.In this case, performing arithmetic operations directly may result in errors or unexpected results.To ensure the accuracy of the calculation, we can useintegerorfloatThe filter explicitly converts the value to an integer or floating-point number:

{# 假设 custom_price_str 是一个字符串“25.50” #}
{% archiveDetail customPriceStr with name="custom_price" %}
<p>字符串价格乘以 2: {{ customPriceStr|float * 2 }}</p> {# 先转换为浮点数再乘 #}

Practical tips and suggestions

  • Variable assignment ({% set %}or{% with %}):When we need to perform more complex calculations, or when we want to store intermediate results for later use,{% set %}and{% with %}Tags are very useful. They can help you organize code and make logic clearer.{% set newVar = someCalculation %}Used to define variables within the current scope, while{% with %}is usually used to temporarily define a group of variables and{% endwith %}end.
  • Combine conditional judgment:Combine conditional judgment{% if %}Tags can make our dynamic display more intelligent. For example, it will only be displayed when the calculation result is positive, or display different prompts according to the different ranges of the results.
  • Note the data type:Although the Anq CMS template engine sometimes tries to automatically convert data types, it is explicitly usedintegerorfloatA filter to ensure that the data involved in the calculation is of the correct numeric type is a good habit, which can avoid potential errors.
  • Handle special cases:When performing division, be especially aware of the case where the denominator is zero. Although the underlying Go language of Anqie CMS usually handles it gracefully, to improve user experience, you can add conditional judgments in the template to avoid directly displaying the result of division by zero, for example{% if totalStockValue > 0 %}.

By flexibly using the above arithmetic operation functions and filters, you can realize rich dynamic number display in the Anqi CMS template, greatly enhancing the interactivity and practicality of website content.


Frequently Asked Questions (FAQ)

1. Why do the numbers concatenate instead of adding when I perform addition operations on them in the template?

This is usually because the 'number' involved in the operation has been identified as a string by the template engine. When a string performs addition

Related articles

How to concatenate the elements of an array into a string separated by a specified delimiter for display?

When managing and displaying content in Anqi CMS, we often encounter situations where we need to merge a group of related information into a coherent text.For example, a product may have many characteristics, and we hope to display the list of these characteristics uniformly with commas or slashes.Or perhaps, an article is associated with multiple keyword tags, and we want to summarize these tags into a single line of text.At this time, the powerful template filter of Anqi CMS can be put to good use, especially the `join` filter, which can help us easily achieve this goal.### Understand the `join` filter

2025-11-08

How to convert timestamp data stored in the background into a readable date and time format for display?

When managing website content in Anqi CMS, we often encounter situations where we need to display dates and times.However, the time information stored in the background database is usually in the form of timestamps, which is very efficient for machine processing, but difficult for users to read directly.For example, you might see a string like `1609470335`, which represents a specific moment, but we want it to be displayed in a more friendly format like "2021 January 1 at 12:25:35".fortunately

2025-11-08

How to format user input plain text content (including newline characters) into HTML paragraphs and newline characters for display?

In website content management, we often encounter such needs: when users input a block of plain text content in the background, it often contains some natural paragraphs and line breaks. We hope that these paragraphs and line breaks are rendered correctly on the website front-end as HTML paragraph tags (`<p>`) and line break tags (`<br/>`), rather than being compressed into a blob or ignored by the browser.AnQi CMS provides a very convenient and powerful template filter to solve this problem, allowing plain text content to be presented elegantly on the web.

2025-11-08

How to extract a part of a long string or HTML content and display an ellipsis at the end?

In website content operation, we often encounter such situations: the article list page needs to display the summary of the content, the product detail page needs to show a brief introduction, or in some special modules, we need to extract a part of the long text or content containing HTML tags, and add "..." at the end to prompt the user that the content is not complete.This not only effectively saves page space and keeps the layout neat, but also improves the reading experience and attracts users to click to view the full content.To achieve such a function, if it were to be manually截取 each time, it would undoubtedly consume a lot of time and effort.Fortunately

2025-11-08

How to generate random placeholder text to simulate real content display during template development?

During the process of website template development, we often encounter a challenge: how to fill the page to check the layout, style, and responsiveness before the real content is ready?If the template is empty or only has a few lines of simple text, it is difficult to evaluate the design effect directly.This is a very useful technique for generating random placeholder text. AnQiCMS (AnQiCMS) is an efficient and customizable content management system that fully considers the needs of template developers at this stage.

2025-11-08

How to ensure that a captcha is displayed when users submit comments or messages to prevent robot abuse?

When operating a website, we often encounter bots submitting a large number of spam messages or comments, which not only affects the quality of the website content but also increases the management burden and may have a negative impact on the reputation of the website.Luckily, AnQiCMS provides an in-built captcha mechanism that can effectively help us prevent such abusive behaviors.Next, let's see how to add a captcha for user comments or reviews in AnQiCMS.

2025-11-08

How to retrieve and display specific content from a specified site in a multi-site management environment?

In today's changing network environment, many businesses and content operators are no longer satisfied with a single site.Scenarios where there are multiple brands, product lines, or the need for multilingual promotion are becoming increasingly common.AnQiCMS (AnQiCMS) is exactly under such needs, providing powerful multi-site management capabilities, allowing us to easily manage multiple content platforms with a single system.But having multi-site functionality is not enough. Often, we need to display specific content from one site on another site, to achieve resource sharing and content synergy.For example, the main site wants to display the latest products of a child site

2025-11-08

How to debug the structure, type, and value of display variables in a template to help troubleshoot display issues?

During the template development process of Anqi CMS, we sometimes encounter situations where variables do not display as expected or the displayed content is incorrect.This may affect the normal functioning of the website, and may also cause deviations in content display, reducing the user experience.We need an efficient and intuitive tool to help us quickly locate the problem.The Anqi CMS provides a very practical built-in filter——`dump`, which can help us clearly view the structure, type, and current value of any variable in the template.

2025-11-08