How to perform simple arithmetic operations (+ - * /) and display the results in AnQiCMS template?

Calendar 👁️ 61

In AnQiCMS templates, we often need to display website content and data.But sometimes, we need not only to display the stored data, but also to perform some simple processing on it, such as calculating the total price of goods, statistics of page loading progress percentage, or adding up a certain number, etc.AnQiCMS template system provides very friendly support for such needs, it has built-in powerful expression processing capabilities, allowing us to perform basic arithmetic operations such as addition, subtraction, multiplication, and division directly in the template, and display the results in real time.

The template syntax of AnQiCMS is similar to Django's template engine, so it will be very easy for users familiar with this syntax to get started. It allows you to use double curly braces{{ ... }}Enter the expression directly, the system will automatically parse and calculate the result.

Perform arithmetic operations directly.

In AnQiCMS templates, performing arithmetic operations is very intuitive, you just need to place operands and operators inside double curly braces as you would in a normal mathematical formula.

Addition (+and subtraction (-)

Imagine that you might want to display the result of adding or subtracting one number from another on a webpage. This is quite easy in the AnQiCMS template.

For example, you have a basic numberbaseValueand you want to increase or decrease it on this basisoffsetValue:

{# 显示两个数字的和 #}
<div>基础数值 + 偏移量:{{ baseValue + offset }}</div>

{# 显示两个数字的差 #}
<div>总金额 - 折扣:{{ totalAmount - discount }}</div>

AnQiCMS's template engine automatically identifies these numbers and performs the corresponding operations, whether they are integers or floating-point numbers, and can achieve accurate results.

Multiplication (*) and division (/)

In e-commerce websites, calculating the total price of a product is a very common requirement, which requires the use of multiplication. For example, if you have a product objectitem, it haspriceandquantityattribute:

{# 计算商品总价 #}
<div>商品总价:{{ item.price * item.quantity }}</div>

Division operations are also intuitive, for example, if you want to calculate a ratio or percentage, such as the proportion of completed tasks to total tasks:

{# 计算任务完成度百分比 #}
<div>完成度:{{ (completedTasks / totalTasks) * 100 }}%</div>

It is worth noting that multiplication and division have higher precedence than addition and subtraction. If you need to change the order of operations, you can use parentheses as in mathematics.()To clarify the priority, make sure to get the expected result.

Modulo (%)

If you need to determine whether a number is a multiple of another number or need to display certain content periodically, the modulo operation (remainder) comes into play.

{# 判断一个数除以3的余数 #}
<div>10除以3的余数是:{{ 10 % 3 }}</div>
{# 输出结果为 1 #}

This is very practical in scenarios where you need to alternate row colors, group display data, etc.

Extend the application:addFilter

In addition to directly in{{ ... }}Perform arithmetic operations in expressions, AnQiCMS also provides some convenient filters (Filters) to help us process data, whereaddA filter is a good example, it can be used to quickly perform addition operations.

addThe main advantage of the filter lies in its flexibility, it can add integers, floating-point numbers, strings, and even mixed types of data.When the type does not match, it will try to perform an intelligent conversion, and if the conversion fails, it will ignore the parts that cannot be added together to avoid template errors.

{# 使用add过滤器进行数字相加 #}
<div>5加上2:{{ 5 | add:2 }}</div>
{# 输出结果为 7 #}

{# 字符串拼接 #}
<div>品牌名称:{{ "安企" | add:"CMS" }}</div>
{# 输出结果为 安企CMS #}

{# 变量与数字相加 #}
<div>文章浏览量增加100:{{ archive.Views | add:100 }}</div>

This approach is particularly convenient when dealing with scenarios that require string concatenation or numerical addition, as it provides a concise and powerful data processing method.

Practical scenarios and considerations

Mastering these basic arithmetic operations, your AnQiCMS template can handle more dynamic data displays.Whether it is the calculation of product prices on the front-end page, generating star ratings based on ratings, or performing simple proportion calculations in data charts, all can be directly implemented at the template level.

In templates, handling such logic can make the page display more flexible and intelligent, reduce the dependency on backend data preprocessing, and improve development efficiency.Of course, if the operational logic is too complex, involving a large amount of data or complex business rules, it is usually recommended to place this logic on the backend. The template is more responsible for display, maintaining simplicity and maintainability.

In short, through simple{{ ... }}expressions and flexibleaddThe filter, AnQiCMS template system has opened the door for us to perform data arithmetic operations directly on the front end.It greatly enhances the dynamics and practicality of the template, making content operation and website management more efficient and convenient.


Frequently Asked Questions (FAQ)

Q1: Can you use template variables or tags directly in arithmetic expressions to return values?

A1: Yes, absolutely. AnQiCMS template engine supports using defined template variables directly in arithmetic expressions, for example{{ item.Price * item.Quantity }}. In addition, some tags (such as{% archiveDetail with name="Views" %}The value can also be used for further arithmetic operations, but it is recommended to assign it to a variable (such as{% set views = archive.Views %}), then perform the calculation to maintain code clarity.

Q2: What complex mathematical operations does the AnQiCMS template support, such as exponentiation or square root?

A2: AnQiCMS template engine supports basic arithmetic operators, including addition (+), subtraction (-), multiplication (*), division (/) and modulus (%). Besides, it also supports exponentiation operations, using^symbol, for example{{ 2 ^ 3 }}You will get 8. For more complex mathematical functions (such as square roots, trigonometric functions, logarithms, etc.), the template engine itself does not provide them directly, and they usually need to be processed by the backend or implemented through custom filters.

Q3: What happens if the divisor is zero during division operation?

A3: When performing division operations in the AnQiCMS template, if the divisor is zero, the template engine usually avoids a direct error report to prevent the page from crashing.It may return a zero value or an empty value, the behavior may vary depending on the template engine version or context.For the sake of safety

Related articles

How to use the `default` filter to set a default display value for possibly empty variables?

In website content management, we often encounter a situation where a certain data variable may not have a value on some pages or under certain conditions, that is, "empty".If the template directly outputs these blank variables, ugly gaps will appear on the page, which not only affects the aesthetics but may also confuse the visitor.In order to avoid such embarrassment, AnQi CMS provides a very practical tool - the `default` filter, which can help us set a graceful default display value for these variables that may be empty.

2025-11-07

How to use the `cut` or `removetags` filter to remove specific characters or HTML tags from strings in the AnQiCMS template?

In AnQi CMS template design, in order to better control the display of content, the system provides a variety of flexible filters (Filter).These filters can help you perform various string processing operations when outputting variables, such as removing specific characters or HTML tags, making the content neater and meeting your display requirements.Today, we will focus on the practical filters `cut` and `removetags`.

2025-11-07

How to convert a numeric string (such as "5.5") to a floating-point number or integer for display and calculation in AnQiCMS template?

In Anqi CMS template development, we often encounter scenarios where we need to handle numeric string.For example, the price stored in the background custom field may be a text type "5.5", or the numbers in the data obtained through the external API may exist as strings.At this point, if a direct numerical operation is performed, problems may arise.However, AnqiCMS's template engine provides very flexible and powerful functions, which can easily convert numeric strings to floating-point numbers or integers and perform subsequent display and calculation.

2025-11-07

How to use `truncatechars` or `truncatewords` filters to truncate long text or HTML content and add an ellipsis?

In website content management, we often encounter such situations: in order to maintain the neat and unified layout of the page, we need to truncate the long text content without destroying its semantics or layout.Whether it is an article summary, product introduction, or user comment, appropriately controlling the length of the text and adding ellipses can greatly enhance the user experience.The template engine of AnQiCMS provides us with two very practical filters: `truncatechars` and `truncatewords`, as well as their variants for handling HTML content

2025-11-07

How to configure the pseudo-static URL rule in AnQiCMS to optimize the display path and SEO friendliness?

In website operation, the URL is not only the address of the page content, but also an important part of search engine understanding, user identification, and brand building.A clear and meaningful URL structure, known as "pseudo-static" or "staticized" URL, is crucial for improving the SEO performance and user experience of a website.AnQiCMS is a content management system that focuses on SEO-friendliness and provides flexible and diverse static URL configuration features, helping us optimize the display path of content better.

2025-11-07

How to display the comment list of an article in AnQiCMS template, including multi-level replies and review status indicators?

In Anqi CMS, let your article page not only be a display of content, but also an active communication platform, and the comment feature is the bridge connecting content with readers.Understanding how to flexibly display an article's comment list in a template, including multi-level replies and clear review status indicators, is crucial for building an interactive website. ### The foundation of comment functionality: Ensure backend configuration is ready Before delving into template code, we first need to confirm that the comment feature is enabled in the AnQi CMS backend.

2025-11-07

How to retrieve and display custom fields in the AnQiCMS template for the website message form and ensure correct submission?

In Anqi CMS, adding and managing custom fields for the website's message form can not only help us collect more specific and targeted customer information, but also significantly enhance the interactivity and data collection efficiency of the website.AnQi CMS with its flexible content model and easy extensibility makes this process very convenient.This article will guide you on how to obtain and display custom fields in the Anqi CMS template and ensure that these fields are submitted correctly.### Step 1: Define the custom message field in the Anqi CMS backend First

2025-11-07

How does AnQiCMS implement anti-crawling interference code through built-in features to protect the display of original content on the front end?

Today, as digital content becomes a core asset, how to effectively protect original content from malicious collection and misuse has become a common challenge for website operators and content creators.Hardly created articles, product descriptions, in a moment may appear on other websites, not only dilute the value of original content, but may also have a negative impact on the search engine rankings of websites.AnQiCMS (AnQiCMS) is fully aware of this pain point and therefore built-in anti-crawling interference code function at the initial stage of system design, aiming to build a clever and sturdy barrier for the display of original content on the front end.

2025-11-07