How to perform addition or other arithmetic operations on numbers or strings in the template?

Calendar 👁️ 86

In website template development, we often need to perform some basic arithmetic operations, such as calculating the sum, adjusting values, or comparing values based on specific conditions.AnQiCMS (AnQiCMS) leverages its efficient architecture based on the Go language and its flexible template engine inspired by Django style, providing users with an intuitive and powerful way to perform arithmetic operations such as addition of numbers or strings in templates.

The template syntax design of Anqi CMS makes technical information presentable in an easily understandable manner in the template without complex backend code, enabling dynamic numerical processing directly on the frontend page.

Flexibly use arithmetic operation tags (calc)

When more complex arithmetic expression calculations, logical judgments, or numerical comparisons are needed, AnQi CMS provides a dedicatedarithmetic operation tagscalcThis tag allows you to directly write mathematical expressions in the template, whose results can be output directly or used for conditional judgments.

You can write mathematical formulas as you would for regular mathematics.{{ ... }}Operations such as addition, subtraction, multiplication, and division are performed within double curly braces. For example, if there is a variable nameditem.Pricerepresenting the price of the product, and anotheritem.Quantityrepresenting the quantity, then the total price can be calculated as follows:

{{ item.Price * item.Quantity }}

More complex expressions, such as those containing parentheses to control the order of operations, are also applicable:

{{ (item.Price * item.Quantity) + ShippingCost }}

In addition to basic addition, subtraction, multiplication, and division,calcTags also support more advanced mathematical operations, such as modulo (%This is very useful in certain scenarios (such as determining odd or even lines or loop cycles).

In terms of logical judgment,calcThe expressiveness of the label is also very good. You can{% if ... %}Comparisons are made directly using the comparison operator (==,!=,<,>,<=,>=) to compare numbers:

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

You can even check if a value exists in a list or a mapping usinginornot inOperators, which bring great flexibility to template logic.

{% if "VIP" in user.Roles %}
  <span>VIP专属内容</span>
{% endif %}

Convenient for addition:addFilter

For the need of just performing addition operations, Anqi CMS provides a more concise one.addFilter. This filter is specifically designed to add two values, whether they are numbers or strings. Its strength lies in its ability to intelligently handle different types of data.

UseaddWhen using a filter, you just need to place the variable you want to operate on after the pipe symbol|in front of the filter nameaddfollowed by a colon:then follow with the value you want to add:

{{ initial_value | add: value_to_add }}

If both operands are numbers, they will be added directly, for example{{ 5 | add: 2 }}will output7. If one or both operands are strings,addthe filter will try to concatenate strings. For example,{{ "Hello " | add: "World" }}will output"Hello World". Even when numbers and strings are mixed, if they can be reasonably converted, they will be added together. Otherwise, they will be concatenated or kept as they are.

This flexible feature allowsaddThe filter is very convenient when it is needed to quickly combine strings or perform simple numerical addition, reducing the trouble of type conversion.

Data type and precision control: making calculations more accurate.

When performing arithmetic operations in the template, data types and precision are important aspects to pay attention to.Although AnQi CMS template engine has certain intelligence in handling type conversion, sometimes we may need to perform explicit type conversion to ensure the accuracy of the calculation result.

integerandfloatFilterWhen you retrieve data from the database, which is by default of string type, and you need to perform numerical operations on it, you can use these two filters to force the conversion to integer or float.

{{ "10" | integer | add: 5 }}  {# 将字符串“10”转换为整数10,然后加5,输出15 #}
{{ "3.14" | float | add: 1.0 }} {# 将字符串“3.14”转换为浮点数3.14,然后加1.0,输出4.14 #}

floatformatFilterFor floating-point arithmetic results, you may need to control the number of decimal places displayed to avoid overly long decimals or unnecessary precision.floatformatThe filter can help you achieve this:

{{ total_price | floatformat:2 }} {# 将 total_price 保留两位小数输出 #}

stringformatFilter: If you need more fine-grained output format control, such as adding thousand separators, padding leading zeros, etc., you can usestringformatfilter, which is similar to the one in Go language,SprintfFunctions provide powerful formatting capabilities.

{{ "总金额: %.2f 元" | stringformat:total_amount }} {# 格式化输出带两位小数的金额 #}

With these filters, you can ensure that arithmetic operations in the template are not only executed correctly but also displayed in a user-friendly format.

Application scenarios in practice

The arithmetic operation function in Anqi CMS template is widely used in daily website operations:

  • Product display pageCalculate and display the product discount price, shipping fee, tax, and final total.
  • Member system:According to the user's points or level, different preferential amounts are displayed, or the rewards obtained by the user are calculated.
  • Content statistics:Display the growth of article reading volume, comment count statistics, and even simple year-on-year and month-on-month calculations.
  • List page interaction: Adjust the style or display hints of list items dynamically based on inventory quantity, user ratings, and other numerical values.
  • Countdown featureCalculate the remaining time until an event (such as the end of an activity, order deadline) occurs.

Summary

The AnQi CMS template engine provides great convenience to website operators and template developers with its built-in arithmetic operation tags and a series of practical filters.Whether it is a simple addition of numbers or complex logical judgments and numerical formatting, it can be easily realized at the template level, greatly enhancing the dynamicity and interactivity of content display.Mastering these features will enable you to build smarter and more efficient websites within the Anqi CMS framework.


Frequently Asked Questions (FAQ)

Q1: Can I directly perform arithmetic operations like addition, subtraction, multiplication, and division in the statement?{% if ... %}Can I perform arithmetic operations like addition, subtraction, multiplication, and division in the statement?A1: It's okay. The AnQi CMS template engine supports using{% if ... %}arithmetic operations, comparison operators (==,!=,<,>,<=,>=), and logical operators (and,or,notPerform arithmetic and logical judgments. For example{% if item.Price * item.Quantity > 100 %}Is perfectly valid.

Q2: If my variable is of string type but actually represents a number, can I perform addition operations directly?A2: For addition, you can useaddFilter. For example, ifvariableIs"10",{{ variable | add: 5 }}It will output15It tries to intelligently convert strings to numbers. But for other operations (such as multiplication or division), or to ensure type strictly, it is recommended to use first.integerorfloatThe filter explicitly converts it to a numeric type, for example{{ variable | integer * 5 }}.

Q3: How can I ensure that my number is always displayed in a specific format in the template, such as two decimal places?A3: You can usefloatformatA filter to control the number of decimal places for floating-point numbers, for example{{ total_amount | floatformat:2 }}Willtotal_amountFormat to two decimal places. For more general string formatting, such as adding currency symbols or percentages,stringformatThe filter provides powerfulSprintfformatting capabilities of style.

Related articles

How to use a filter to truncate the specified character length of an article description or abstract and automatically add an ellipsis?

In website operation, the presentation of article description or abstract is crucial for user experience and Search Engine Optimization (SEO).A well-balanced, concise summary that not only attracts visitors to click but also helps search engines better understand the page content.However, manually controlling the length of each article summary is time-consuming and prone to errors.Fortunately, AnqiCMS provides powerful template filter functions that can help us automate this process, ensuring the uniformity and beauty of website content display.Why is it necessary to truncate article descriptions or summaries

2025-11-08

Besides `stampToDate`, which filters can format time values into a specified date format?

In AnQi CMS template development, we often need to display the time values stored in the database, such as the publication time and update time of articles, in the date and time format we expect.The `stampToDate` filter is undoubtedly one of the most commonly used and powerful tools, which can flexibly convert Unix timestamps to various date formats.

2025-11-08

How to combine custom parameters (such as "area", "house type") for multi-condition filtering on the article list page?

In AnQi CMS, to implement multi-condition filtering on the article list page, such as filtering based on custom parameters such as "area" and "house type", it requires us to cleverly combine the system-provided "content model" feature with the "document parameter filtering tag" ("archiveFilters") and "document list tag" ("archiveList") of the front-end template.The entire process can be divided into several core steps, let's take a detailed look together.### Core Function: Customize Content Model and Parameters Basic Implementation of Multi-Condition Filtering

2025-11-08

How to implement search through URL parameters (such as `q=keyword`) on the article list page and display the results?

It is crucial to provide users with a convenient and accurate content search experience in website content operation.When the number of articles on the website continues to grow, a practical search function can greatly enhance user satisfaction and the efficiency of content access.AnqiCMS as an efficient content management system provides a flexible way to implement the URL parameter search function for the article list page, allowing visitors to directly search and view related content by adding parameters such as `q=keywords` to the URL.

2025-11-08

How to set a default display value for a possibly empty variable, string, or object?

In website content management, the integrity and consistency of data are crucial.However, in actual operation, we often encounter situations where certain variables, strings, or objects may be empty.If the template does not handle these null values properly, the front-end page may appear blank, disordered, or even report errors, severely affecting user experience.AnQiCMS provides various flexible and powerful template tags and filters, helping us elegantly handle potential null values to ensure the stability and beauty of website content.The AnQi CMS template system borrows the syntax from Django

2025-11-08

How to use a filter to remove specific characters (such as spaces) from the beginning, end, or any position of a string?

String cleaning practical guide in AnQiCMS: Efficiently remove filters for specific characters During the operation of a website, we often encounter situations where we need to clean and format string data.Whether it's the extra spaces typed by users or redundant characters carried in when importing content from external sources, these subtle details may affect the neatness of website content and the user experience.AnQiCMS (AnQiCMS) provides a multifunctional and easy-to-use template filter that can help us easily deal with these string cleaning needs.

2025-11-08

How to use a filter to automatically find URLs in text and convert them into clickable HTML links?

In website operation, we often encounter such needs: in the content or description of the article, some URLs or email addresses may be included, but they are just plain text, and users cannot click to access directly.Manually adding HTML links to each URL is inefficient and prone to errors, especially when the volume of content is large.AnQiCMS (AnQiCMS) understands this pain point and provides powerful built-in filters to help us easily automate the conversion of URLs in text, making website content more friendly and convenient.### Automated Link

2025-11-08

How to ensure that HTML code is correctly parsed and not escaped when displaying rich text content using the `safe` filter?

In AnQi CMS, rich text content usually carries articles, product descriptions, or page details with rich information. This content often includes various HTML tags such as bold, italic, images, links, tables, and so on.If this HTML code is not parsed correctly and is simply displayed as plain text, then what the user sees on the front end is a pile of code, rather than beautiful and structured content. This clearly has a negative impact on the readability and professionalism of the website.

2025-11-08