How does the `add` filter work for adding numbers or concatenating strings in templates?

Calendar 👁️ 75

In AnQi CMS template design, we often need to perform some simple data processing, such as adding several numbers to display the total, or combining different text segments into a complete sentence. At this point,addThe filter is particularly convenient, acting as a universal connector that can easily handle everything from numerical addition operations to text concatenation, making your template more flexible and dynamic.

addFilter: The smart connector in the template

As the name implies,addThe main function of the filter is to add two values together.Its intelligence lies in the fact that it can not only handle pure numerical addition, but also cleverly concatenate numbers with strings, and strings with strings.This is due to the internal processing mechanism of the AnQiCMS template engine, which tries to intelligently perform type conversion to achieve the expected "addition" effect.

While usingaddWhen filtering, the syntax is very intuitive: you just need to place the first value after the pipe symbol|on the left, and theaddThe filter and its second operand are placed on the right, like this:{{ 变量A|add:变量B }}.

It is worth noting that even if you pass toaddThe filter handles different types of values, such as a number and a string, and AnQiCMS template engine will also try to convert and process them.If it cannot perform an effective numeric addition or string concatenation, it will silently ignore the parts that cannot be converted, ensuring the normal rendering of the template without causing the page to report an error.This fault-tolerant mechanism allows template developers to feel more at ease when combining content.

Actual application: adding numbers and concatenating strings

Let's look at some specific examples to see.addHow the filter works in your AnQiCMS template.

Flexible addition of numbers

When you need to calculate and display the sum of two or more numbers,addThe filter is an ideal choice. For example, you might need to add the unit price of the goods and shipping costs, or calculate some statistical data.

Assuming you have a variablepriceStore the price of the goods as100Another variableshipping_feeStore shipping costs as20The total amount you want to display:

{% set price = 100 %}
{% set shipping_fee = 20 %}

<p>商品总价:{{ price|add:shipping_fee }} 元</p>

This code will output:商品总价:120 元.

This applies to integers as well as floating-point numbers, ensuring the accuracy of calculations.

Seamless concatenation of strings

In addition to adding numbers,addThe filter performs well in processing string concatenation.When you need to combine different text segments, dynamic content, or preset words together, it can provide a very smooth experience.

For example, do you want to concatenate your CMS system name 'Anqi' with 'CMS':

<p>我们的系统是:{{ "安企"|add:"CMS" }}</p>

This code will output:我们的系统是:安企CMS.

If you have a dynamic brand name or suffix, you can also easily combine it:

{% set brand = "AnQi" %}
<p>我们提供的产品:{{ brand|add:"CMS" }}</p>

The output will be:我们提供的产品:AnQiCMS.

A clever combination of numbers and strings

addThe true charm of the filter lies in its ability to intelligently combine numbers and strings. This is very useful in scenarios such as building dynamic links, displaying version numbers with numbers or IDs, etc.

For example, you have an article IDarticle_idWith123And you want to add a prefix 'Article Number-' when displaying it, you can do it like this:

{% set article_id = 123 %}
<p>文章编号:{{ "文章编号-"|add:article_id }}</p>

The output will be:文章编号:文章编号-123.

You can also put the number in front:

{% set version = 2 %}
<p>当前版本号:{{ version|add:".1.0" }}</p>

The output will be:当前版本号:2.1.0.

Please note that in this mixed type operation, the string part is directly connected to the numeric part, rather than trying to convert the string to a number for mathematical addition.This behavior usually meets our expectations.

Handle null values and unexpected situations

addAnother practical aspect of the filter is its handling of null values. If you try to add a number with a non-existent (nothingOr adding a variable with an empty string will show good error tolerance.

{% set count = 5 %}
{% set nothing_value = nothing %} {# nothing表示变量未定义或为空 #}

<p>计算结果1:{{ count|add:nothing_value }}</p>
<p>计算结果2:{{ "安企"|add:nothing_value }}</p>
<p>计算结果3:{{ 5|add:"CMS"|add:nothing_value }}</p>

The output of this code will be:计算结果1:5 计算结果2:安企 计算结果3:5CMS

As you can see,addThe filter will ignore null values directly, returning only valid values, which is very convenient when dealing with templates that may contain null data, and avoids additional conditional judgment.

Summary

addThe filter is a seemingly simple but powerful tool in the AnQiCMS template engine, playing an important role in simplifying template logic and enhancing content dynamics. Whether it is pure numerical addition, flexible string concatenation, or a clever combination of both, addFilters can process with intelligent types and good error tolerance, helping you build rich and diverse website content more efficiently.Reasonably utilizing this filter can make your template code more concise and easier to maintain, allowing you to focus on the presentation of content itself.


Frequently Asked Questions (FAQ)

1.addDoes the filter support subtraction, multiplication, or division operations?

addThe filter is specifically used for the addition of numbers and concatenation of strings.It does not support direct subtraction, multiplication, or division operations.算术运算标签To get more information and usage methods.

2. If I need to add multiple strings or numbers consecutively,addHow to write a filter?

When you need to combine multiple values consecutively, you can do so like a pipeline andaddchain filters together. For example, if you want to combine three numbers or stringsvalue1/value2andvalue3Add consecutively, you can write it like this:{{ value1|add:value2|add:value3 }}The template engine will process these operations from left to right.

3.addWhat is the difference between the filter in processing Chinese and English?

addThe filter does not make any essential difference when processing Chinese and English strings.It will treat them all as ordinary text characters for concatenation.Whether it is Chinese, English, or characters of other languages, they will be connected in the order they appear in the string without affecting their function or performance.

Related articles

How do the `removetags` and `striptags` filters remove specific or all HTML tags from HTML content?

In Anqi CMS, when managing website content, we often encounter such situations: articles imported from outside, comments submitted by users, or code generated by rich text editors may contain various HTML tags.These tags are sometimes necessary, but more often, they may disrupt the page layout, introduce unnecessary styles, and even pose potential security risks. 幸运的是,AnQiCMS provides two very practical template filters —— `removetags` and `striptags`

2025-11-07

In which scenarios must the `safe` filter be used to prevent HTML content from being automatically escaped?

When using AnQiCMS for website content management and template development, we often encounter a problem related to HTML content display: Why does the rich text content I edit in the background display as a pile of original code with angle brackets on the front end, rather than a beautifully formatted effect?This is actually the "auto-escape" mechanism of AnQiCMS template engine at work, and to solve this problem, the `safe` filter has become the key tool we must master.### Why does automatic escaping occur? AnQiCMS

2025-11-07

How do the `urlize` and `urlizetrunc` filters automatically convert URLs in text to clickable links?

It is crucial to present information efficiently and aesthetically in website content operations.Especially when the content contains a large number of URLs or email addresses, manually converting them into clickable links is not only inefficient but also prone to errors.AnQiCMS (AnQiCMS) is well-versed in this, its template system provides the practical filters `urlize` and `urlizetrunc`, which can automatically identify URLs in text and intelligently convert them into clickable hyperlinks, greatly enhancing user experience and content management efficiency.###

2025-11-07

How do the `truncatechars` and `truncatewords` filters control the truncation display of long text and add an ellipsis?

In website content operation, we often encounter such situations: In order to maintain the neatness and consistency of the page layout, we need to truncate the long text, such as in article lists or product summaries.If cut off simply and brutally, it may not only result in incomplete meaning of the text, but may also destroy the text structure containing HTML tags, affecting the aesthetics and functionality of the page.AnQi CMS, with its flexible template engine, provides us with an elegant solution to this problem.Through built-in text filters, we can easily control the display length of long texts and add ellipses at appropriate positions

2025-11-07

How `default` and `default_if_none` filters set a default display value for possibly empty variables?

In website content management, we often encounter situations where variable values may be empty.These empty values, if displayed directly on the front-end page, may lead to incomplete content display, page layout disorder, and even a bad user experience.AnQiCMS (AnQiCMS) as a powerful content management system, the Django template engine syntax it adopts provides us with a flexible way to handle such issues.

2025-11-07

How `length` and `length_is` filters are used to check the length of a string, array, or map?

In Anqi CMS template development, flexible handling and displaying data is the key to improving website interactivity and user experience.Understanding how to efficiently detect the length of strings, arrays, or mappings (similar to dictionaries or associative arrays in other programming languages) is the foundation for content operations and template customization.This article will introduce in detail the `length` and `length_is` practical filters in the Anqi CMS template engine, which will help you better control the display of page content.### `length` filter

2025-11-07

The `contain` filter how to determine if a string or array contains a specified keyword?

In Anqi CMS template development, flexibly controlling the display of content is the key to improving website user experience and operational efficiency.Sometimes, we may need to determine whether a piece of text, a list (array), or a data object (Map/Struct) contains a specific keyword or property.At this time, the `contain` filter provided by Anqi CMS can give full play to its role, it can help us easily achieve this kind of conditional judgment, making the template logic more intelligent.What is the `contain` filter?

2025-11-07

How does the `count` filter count the occurrences of a specific keyword in a string or array?

In AnQi CMS template development, efficiently handling and analyzing content is the key to enhancing website interactivity and information display capabilities.Sometimes, we need to know how many times a specific word appears in a piece of text, or how many times a specific element is included in a data list.This is when the `count` filter comes into play.It is a very practical tool that can help us quickly count the occurrences of a specific keyword in a string or an array (slice).

2025-11-07