How can the `add` filter be used to perform exact addition of numbers in the Anqi CMS template?

Calendar 👁️ 64

In Anqi CMS template development, we often need to perform calculations on numbers, such as counting the total price of a product or dynamically adjusting the display quantity. The Anqi CMS template engine provides rich filters to handle these scenarios, includingaddThe filter is a powerful tool for implementing numeric addition or string concatenation. It uses its intelligent type handling mechanism to allow developers to more flexibly deal with data calculation needs in templates.

addFilter: Smartly handles the addition of numbers and strings

addThe core function of the filter is to perform addition of two values.It lies in its uniqueness, not limited to pure numerical addition, but also capable of intelligently handling scenarios involving the mixing of numbers and strings.When both operands are numbers, it performs regular mathematical addition.When one or both of the operands are strings,addThe filter will attempt to convert the string to a number, if successful, then perform addition;If it cannot be converted to a number, it will perform string concatenation.This flexible mechanism greatly simplifies the data processing logic in the template.

UseaddThe basic syntax of the filter is very intuitive:

{{ obj|add:obj2 }}

Among themobjIs the first operand,obj2It is throughaddThe second operand passed to the filter.

Actual application scenarios and examples

In order to understand betteraddThe power of the filter, we demonstrate its different usages through several common examples.

1. Addition of pure numbers

This isaddThe most direct usage of the filter, applicable to addition between two integers or floating-point numbers.

{# 示例:计算两个整数的和 #}
{{ 5|add:2 }} {# 输出:7 #}

{# 示例:计算两个浮点数的和 #}
{{ 3.14|add:2.5 }} {# 假设输出:5.64 #}

{# 示例:数字与变量相加 #}
{% set quantity = 10 %}
{% set price = 15 %}
库存总量:{{ quantity|add:price }} {# 输出:25 #}

2. Add numbers with numeric strings

When one operand is a number and the other is a numeric string,addThe filter tries to convert the string to a number and then perform addition.

{# 示例:整数与数字字符串相加 #}
{{ 5|add:"2" }} {# 输出:7 #}

{# 示例:浮点数与数字字符串相加 #}
{{ 3.14|add:"0.86" }} {# 输出:4.0 #}

3. Concatenating a number with a non-numeric string

This isaddAnother manifestation of the filter's intelligent processing. IfaddThe filter finds an operand that is a number and another operand that is a string that cannot be converted to a number, and it will resort to concatenating them as strings.

{# 示例:数字与普通字符串拼接 #}
{{ 5|add:"CMS" }} {# 输出:5CMS #}

{# 示例:将ID与描述信息拼接 #}
{% set item_id = 1001 %}
{% set item_type = "商品" %}
产品编号:{{ item_id|add:item_type }} {# 输出:1001商品 #}

4. Pure string concatenation

When both operands are strings,addThe filter works like traditional string concatenation.

{# 示例:两个字符串拼接 #}
{{ "安企"|add:"CMS" }} {# 输出:安企CMS #}

{# 示例:拼接带空格的字符串 #}
{{ "hello "|add:"world" }} {# 输出:hello world #}

5. Handling null values (nil/nothing)

In the template, data may sometimes be missing or benil.addThe filter behaves quite robustly when encountering such values, it will directly ignore these null values and only perform operations or concatenations on valid data.

{# 示例:数字与空值相加 #}
{{ 5|add:nothing }} {# 假设 nothing 为空值,输出:5 #}

Use suggestions and precautions

  • Clarify the operation intention:While usingaddWhen filtering, it is best to be clear about whether you want to perform numeric addition or string concatenation.Although it is intelligent, clear intention helps to avoid unexpected results.For example, if you need to ensure that you are adding numbers, you can first useintegerorfloatThe filter converts the value to a numeric type.
  • Debug and verification:If the calculation result does not meet the expected outcome, you can utilizedumpThe filter to check the actual type and value of the variable, which helps to quickly locate the problem.
  • Avoid over complexity:ThoughaddThe filter provides flexibility, but for calculations involving multiple operations or complex logic, it is recommended to process data on the backend and only perform simple display layer calculations in the template.

By flexible applicationaddThe filter allows AnQi CMS users to efficiently handle combinations of numbers and strings in templates, thereby building more functional and accurately presented website pages.

Frequently Asked Questions (FAQ)

  1. addDoes the filter support subtraction, multiplication, division, and other arithmetic operations? addThe filter is specifically used for addition operations and intelligent string concatenation. For other arithmetic operations such as subtraction, multiplication, and division, the Anqi CMS template engine provides special arithmetic operation tags (such astag-calc.mdmentioned{{ 10-100 }}or{{ 2 * 5 }}These operators can be directly used in template expressions.

  2. How can I ensure that my variable is a numeric type before adding to avoid unnecessary string concatenation?To ensureaddThe filter performs pure numeric addition, you can useintegerorfloatThe filter first converts the variable to a numeric type. For example:{{ some_string_value|integer|add:10 }}Can ensuresome_string_valueIt is treated as an integer before addition.

  3. addUnder what circumstances will the filter perform string concatenation instead of numerical addition? addThe filter will perform string concatenation in the following two main cases:

    • When one of the operands is a string and the string cannot be effectively parsed as a number (for example{{ 5|add:"不是数字" }}It will output.5不是数字)
    • When both operands are strings (for example{{ "Hello "|add:"World" }}It will output.Hello WorldIt will first try to perform numeric addition, and only if it cannot complete the numeric addition will it fall back to string concatenation.

Related articles

How to dynamically obtain and display the unique user group in the template

In AnQiCMS template, dynamically obtaining and displaying the unique identifier of the user group is a key step to achieving personalized content display and user permission management on the website.AnQiCMS provides flexible and powerful template tags to help us easily achieve this goal.Next, we will discuss how to use these tags to accurately obtain and present user group information. ### Understanding User Group Identification in AnQiCMS In AnQiCMS, user groups are the foundation for managing user permissions and content access.

2025-11-07

What will the `userGroupDetail` tag return if the user group ID or Level does not exist, and how should it be handled?

In AnQiCMS template development, the `userGroupDetail` tag is undoubtedly the core tool for obtaining user group information, allowing us to flexibly retrieve detailed information according to the user group ID or level, thus realizing member level display, specific content access permission control, and other functions.However, in practical applications, we often encounter a problem: what will this tag return when the requested user group ID or Level does not exist?How should we properly handle this situation to avoid unexpected blank pages or error messages on the page

2025-11-07

How to make conditional judgments in the template using the `userGroupDetail` tag to get the user group level (`Level`)?

When managing users and content in AnQiCMS, we often encounter the need to display different content based on user identity, such as exclusive articles that only VIP members can watch, or different function buttons that users of different levels can see.At this time, the `userGroupDetail` tag and the user group level (`Level`) it retrieves become the key tool for us to implement conditional judgment in the template.AnQiCMS as a flexible and efficient content management system, its template engine provides friendly support for Django template syntax

2025-11-07

How to ensure that the `userGroupDetail` tag returns the correct context of the current page?

Running a website on AnQi CMS, flexibility and accuracy are crucial.Especially when we need to display content based on user identity or specific requirements, ensuring that the user group data obtained matches the context of the current page is the basis for personalized experience and permission control.Today, let's delve into how to make full use of the `userGroupDetail` tag to ensure that we can always obtain the correct user group data.

2025-11-07

How does the `add` filter seamlessly concatenate the values of two string variables?

In AnQiCMS template development, we often need to combine different data fragments, whether it is the calculation of numbers or the integration of text information.Among them, the `add` filter is a very practical and flexible tool that can help us easily perform the "addition" operation of two variable values, achieving seamless splicing effects.The design philosophy of the `add` filter is to take into account both numeric calculations and string concatenation.When you apply it to two numeric variables, it performs standard mathematical addition to calculate their sum.

2025-11-07

In AnQiCMS template, why does `{{ 5|add:"CMS" }}` output `5CMS`? What are the rules for mixing numbers and strings in concatenation?

In AnQiCMS template development, we sometimes encounter some seemingly simple expressions that hide clever logic.Among the phenomenon that `{{ 5|add:"CMS" }}` finally outputs `5CMS`, it often makes friends who are new to it feel curious.This involves the unique rule of mixed number and string splicing in AnQiCMS template engine.Today, let's delve deeper into this interesting mechanism.### The "filter" in AnQiCMS template and the magic of `add` In AnQiCMS

2025-11-07

How do you handle the case when one of the variables is `nothing` or `nil` while using the `add` filter, and what will be the output result?

In AnQiCMS template development, we often need to perform simple addition operations or string concatenation, the `add` filter is created for this purpose.It is very convenient to use, and can intelligently handle addition of numbers and concatenation of strings.If you give it two numbers, it will perform mathematical addition;If you give it two strings, it will concatenate them.Even if it is a mixture of numbers and strings, AnQiCMS will try to make a reasonable conversion and output the result.For example, add numbers: twig {{ 5|add:2 }} {#

2025-11-07

How to dynamically add 'Read More' link text to each title on the AnQiCMS article list page?

When managing and operating a website, the article list page is an important entry for users to browse content and discover information.To enhance user experience, clearly guiding visitors to enter the article details, it is a common practice to dynamically add a "Read More" or "View Details" link text to each title in the list.AnQiCMS (AnQiCMS) provides a powerful and flexible template system, allowing us to easily achieve this feature.

2025-11-07