How can simple mathematical arithmetic operations be performed in the AnQiCMS template to display the result?

Calendar 👁️ 66

Handling numerical calculations in AnQiCMS templates is an important aspect for the dynamic and personalized display of website data.No matter what you need to calculate the total price of goods, display discount information, or make conditional judgments based on certain numbers, AnQiCMS's powerful template engine can provide flexible support.Thanks to its Django template engine features, simple mathematical arithmetic operations can be performed directly in the template without complex code logic.

Perform expression calculation directly in the template

AnQiCMS template engine supports double curly braces{{ }}Perform various mathematical arithmetic operations internally, which is very similar to many modern template languages such as Django, Blade, and so on.You can use common operators in programming languages to perform operations such as addition, subtraction, multiplication, and division on numbers and variables.

Let's take a look at some commonly used arithmetic operations and their usage:

1. Addition (+)When you need to add two numbers together, you can simply use the plus sign. For example, if you have a product priceitem.Priceand a taxtax, and you want to display the final price including tax:

{{ item.Price + tax }}

Or, if you want to calculate the sum of two variables:

{{ quantity + bonus }}

2. Subtraction (-)Subtraction operations are also intuitive. For example, calculating the price after a discount:

{{ originalPrice - discountAmount }}

Or display the remaining stock quantity:

{{ totalStock - soldAmount }}

3. Multiplication (*)Multiplication is often used to calculate total prices or ratios. For example, to calculate the cumulative price of multiple products:

{{ item.Price * item.Quantity }}

Or to calculate a percentage:

{{ totalSales * 0.15 }} {# 计算15%的销售额 #}

4. Division (/)Division can be used to calculate an average or distribute a proportion. For example, to calculate the average number of visits:

{{ totalViews / numberOfPosts }}

It should be noted that if the divisor is zero, the system will usually return an error or a special value, and therefore, in practical applications, you may need to cooperate with conditional judgments to avoid such situations.

5. Modulo (%)The modulo operation returns the remainder when two numbers are divided. This is very useful for determining whether a number is odd or even, or for implementing interval styles in loops. For example, to determine whether a product ID is even:

{% if item.Id % 2 == 0 %}
    <div class="even-item">{{ item.Title }}</div>
{% else %}
    <div class="odd-item">{{ item.Title }}</div>
{% endif %}

Hereitem.Id % 2will return0(Ifitem.IdIs even or1(Ifitem.IdThen compare with0.

6. Comparison operationIn addition to direct arithmetic operations, you can also perform comparisons between numbers in the template, which is very common in conditional judgments. Common comparison operators include:

  • Equal (==)
  • Not equal (!=)
  • less than (<)
  • greater than (>)
  • less than or equal to (<=)
  • greater than or equal to (>=)

these comparison operators are often used with{% if %}Use tags together:

{% if product.Stock <= 5 %}
    <span style="color: red;">库存紧张!</span>
{% endif %}

{% if user.Level >= 3 %}
    <p>恭喜您成为VIP用户!</p>
{% endif %}

7. Logical OperationsLogical operators allow you to combine multiple conditions. Common logical operators include:

  • And (andor&&)
  • Or (oror||)
  • Not (notor!)

For example, check if a product is in stock and within a specific price range:

{% if product.Stock > 0 and product.Price < 100 %}
    <p>这是一个热门的实惠商品!</p>
{% endif %}

{% if user.IsAdmin or user.IsEditor %}
    <p>您有权限编辑此内容。</p>
{% endif %}

{% if not article.IsPublished %}
    <p>本文仍在草稿箱中。</p>
{% endif %}

Use variables for calculations:Variables defined in the template can directly participate in calculations, for example, fromarchiveDetailLabel gets document details,systemLabel gets system settings, etc.

{% archiveDetail productPrice with name="Price" %}
{% system shippingCost with name="ShippingCost" %}
<p>商品总价 (含运费):{{ productPrice + shippingCost }} 元</p>

Ensure the variable you get is numeric, otherwise it may cause the calculation result to be inaccurate.

Use the filter for calculation

AnQiCMS's template engine also provides a series of filters that can perform various transformations and processing on variables, including some related to numerical calculations.

1.addFilter addThe filter is specifically used to perform addition operations, and it is very convenient in chained operations.

{{ number|add:5 }} {# 将 number 的值加上 5 #}

This filter can be used for both numbers and string concatenation.

{{ "Hello "|add:"World!" }} {# 输出 "Hello World!" #}

2.divisiblebyFilterThis filter can check if a number can be divided by another number, returning a boolean value.

{% if productId|divisibleby:3 %}
    <p>这是第三组的商品。</p>
{% endif %}

3. Type conversion filter (integer,float)Sometimes the values received from a database or external input may be of string type, but you need to perform mathematical operations on them.integerandfloatFilters can convert these strings to the corresponding numeric type.

{{ "100"|integer + 20 }} {# 结果为 120 #}
{{ "3.14"|float * 2 }} {# 结果为 6.28 #}

If the conversion fails, they will return0or0.0.

4.stringformatFilterAfter completing the calculation, you may need to format the result into a specific string format, such as retaining two decimal places.stringformatThe filter can achieve this, it is similar to programming languages inprintfFunction.

{{ (totalAmount * 1.05)|stringformat:"%.2f" }} {# 计算含5%税的总额并保留两位小数 #}

Example of practical scenarios

Suppose you are building a product list page and want to display the sequence of each product

Related articles

How to format a timestamp into the display format of "Year-Month-Day" in AnQiCMS?

In daily website operations, the display format of dates is crucial to user experience.A clear, consistent, and easy-to-understand date format that allows visitors to easily obtain information and enhance the professionalism of the website.For users of AnQiCMS, we often encounter data stored in the form of timestamps for content publishing time, update time, and so on. How to convert these long strings of numbers into a friendly display format such as 'Year-Month-Date' is an indispensable part of content presentation.

2025-11-08

How to safely extract strings or HTML content and add an ellipsis in AnQiCMS templates?

When operating a website, we often need to display article summaries, product descriptions, or user comments and the like.This text, if not processed, is displayed directly and completely. Long text may disrupt the page layout, affecting the overall aesthetics and information transmission efficiency.This is particularly important to truncate the content appropriately and add an ellipsis.AnQiCMS as an efficient and customizable content management system, its powerful template engine developed based on the Go language provides us with a simple and intelligent solution.Pass through built-in filters (filters)

2025-11-08

How to debug template in AnQiCMS and view the structure and value of variables (using dump filter)?

When developing website templates, we often encounter such confusion: what data does a variable in the template contain?What is its structure? What is the type? And what is the specific value?If these questions cannot be answered quickly, the debugging process will become extremely繁琐and time-consuming.Fortunately, AnQiCMS has provided us with a powerful and convenient debugging tool——`dump` filter, which can help us easily reveal the true face of variables.AnQiCMS developed in Go language, using a template engine syntax similar to Django

2025-11-08

How to generate random text of a specified length as placeholder content in AnQiCMS template?

## Generate random text of a specified length as placeholder content in AnQiCMS template During website development and content operation, we often encounter scenarios where we need to fill in placeholder content (Placeholder Content).Whether it is designing a new template, testing page layout, or giving an initial preview when the content is not fully ready, placeholder text can help us quickly build prototypes, intuitively evaluate the visual effects, and do not need to wait for the real content to be filled in.

2025-11-08

How to split a string into an array by a specified separator and iterate and display it in the template in AnQiCMS?

In website operations and content management, we often encounter such scenarios: a certain field in the background stores multiple related information, such as multiple keywords of an article, various functional tags of a product, or multiple aliases of an author.This information is usually connected into a string with commas, semicolons, or other specific symbols.When it is necessary to display this information one by one or perform style processing in the website front-end template, it is necessary to split this string into independent items and then traverse and display them one by one.AnQiCMS provides a powerful and flexible template engine, its syntax style is similar to

2025-11-08

How to remove specific characters or spaces from a string in AnQiCMS template?

In website content management, string processing is inevitable and crucial.In order to maintain the beauty of the page, keep the standardization of data output, or for SEO optimization, we often need to make fine adjustments to text content, such as removing extra spaces, punctuation marks, or other specific characters.AnQiCMS provides a flexible and powerful template engine, allowing us to easily implement these string operations in front-end templates.

2025-11-08

How does AnQiCMS determine if a string or array contains a specific keyword and display content accordingly?

In website operation, we often need to dynamically adjust the display of the page based on the specific attributes or keywords of the content.For example, when the article title includes the words 'latest', we may want to add a prominent 'NEW' label; or when a product description mentions 'Free Shipping', an icon showing free shipping should be automatically displayed.AnQiCMS (AnQiCMS) provides powerful template functions and rich filters, making it easy to meet these needs.

2025-11-08

How does AnQiCMS handle image resource management and optimization?

In the daily operation of websites, images are not only an important part of the content, but also a key factor affecting website performance and user experience.Efficient image resource management and optimization, can significantly improve website loading speed, improve search engine rankings, and effectively protect the copyright of original content.AnQiCMS is a system born for content operation, which provides comprehensive and practical functions in image processing to help us easily meet these challenges.### A comprehensive centralized management of image resources AnQiCMS provides a centralized management platform for image resources

2025-11-08