How does the `add` filter handle string concatenation operations?

Calendar 👁️ 55

When developing templates for Anqi CMS, we often encounter scenarios where we need to combine text fragments or numbers for display.No matter whether it is to build dynamic page titles, concatenate URLs, or perform simple numerical calculations on the page, flexible data processing capabilities are crucial.AnQi CMS template engine provides a very practical tool——addA filter that can help us easily implement string concatenation and arithmetic operations.

What isaddFilter?

addThe filter is a powerful and flexible built-in filter in the Anqi CMS template, whose core function is to perform the "addition" operation.This 'addition' is not limited to traditional numerical operations, but also includes string concatenation.This means you can use the same filter to process different types of data, reducing the complexity of template code.

addThe filter has intelligent adaptability when processing different data types. It will try to automatically convert and calculate based on the type of input value:

  • When dealing with numbers:addThe filter performs standard arithmetic addition.
  • When dealing with strings:addThe filter concatenates the two strings directly, forming a new string.
  • When dealing with mixed types:addThe filter will try to convert one of the values to a compatible type for the operation.If it cannot be successfully converted and perform effective addition or concatenation, it will usually gracefully ignore the parts that cannot be processed, or concatenate them as strings.
  • When handling null values (nothing/nil) at: If the value involved in the operation is null (ornil)addthe filter usually treats it as0In string concatenation, it is treated as an empty string. If a null value causes an operation to fail, it will be ignored.

addBasic usage of the filter

addThe filter uses the pipe symbol|The way to apply it to a variable, its basic syntax structure is as follows:

{{ obj1|add:obj2 }}

Among them,obj1Is the first value you want to operate (can be a variable or a literal),addIs the name of the filter,obj2Is through the colon:The second value passed to the filter (it can also be a variable or a literal).

For example, if you want to add numbers5and2You can write it like this:

{{ 5|add:2 }}

This will be displayed on the page.7.

addFilter application examples in different scenarios

In order to understand betteraddThe flexibility of the filter, let's look at some specific examples:

1. Add numbers

When both operands are numbers,addThe filter performs regular mathematical addition:

{{ 5|add:2 }}          {# 显示结果: 7 #}
{{ 5|add:40 }}         {# 显示结果: 45 #}

2. String concatenation

This isaddOne of the most commonly used scenarios in content operation, used to combine different text segments:

{{ "安企"|add:"CMS" }} {# 显示结果: 安企CMS #}
{{ "Hello, "|add:"world!" }} {# 显示结果: Hello, world! #}

3. Mixed type operations

addThe filter performs very intelligently in scenarios involving mixed numbers and strings. It tries to convert numbers to strings, then concatenate them, or convert strings to numbers for calculation (if the string is a valid number):

{{ 5|add:"CMS" }}      {# 显示结果: 5CMS (数字5被转换为字符串'5'后与'CMS'拼接) #}
{{ "安企"|add:"2" }}   {# 显示结果: 安企2 (字符串'2'与'安企'拼接) #}

It should be noted that if the string cannot be parsed as a valid number, it will be processed as a string concatenation.

4. Handling null values (nothing/nil)

WhenaddThe filter encountersnothingornilWhen a value... it will be processed according to the context:

{% set emptyVar = nothing %}
{{ 5|add:emptyVar }}   {# 显示结果: 5 (emptyVar被视作0, 5+0=5) #}
{{ "前缀"|add:emptyVar|add:"后缀" }} {# 显示结果: 前缀后缀 (emptyVar被视作空字符串) #}

5. More comprehensive examples

{# 假设我们有一个变量 article.Title = "安企CMS新功能" 和 article.CreatedYear = 2023 #}
{% set articleTitle = "安企CMS新功能" %}
{% set articleYear = 2023 %}
{% set authorName = "运营团队" %}

<p>标题:{{ articleTitle|add:" 发布于 " }}{{ articleYear }}</p>
{# 显示结果: 标题:安企CMS新功能 发布于 2023 #}

<p>作者:{{ authorName|add:" (CMS专家)" }}</p>
{# 显示结果: 作者:运营团队 (CMS专家) #}

<p>文章ID: {{ 100|add:"-ABC" }}</p>
{# 显示结果: 文章ID: 100-ABC #}

Summary

addThe filter is a very convenient and versatile tool in Anqi CMS template, which provides great convenience in string concatenation and number addition. By using it flexiblyaddFilter, you can build dynamic content more efficiently, optimize page display, and make template code more concise and easy to maintain.Remember its core principles: adding numbers, string concatenation, intelligent handling of mixed types, and reasonable handling of null values.


Frequently Asked Questions (FAQ)

1.addCan the filter concatenate or add multiple values at the same time?

addThe filter is a binary operator, which means it can only handle two values at a time. If you need to concatenate or add three or more values, you need toadduse filters in sequence. For example:{{ "A"|add:"B"|add:"C" }}It will calculate first"A"|add:"B"Get"AB"Then it will"AB"|add:"C"Get"ABC".

2. If I just want to display two strings next to each other, useaddfilter and write directly{{str1}}{{str2}}What is the difference?

For pure string concatenation without involving numerical operations, write directly{{str1}}{{str2}}It is usually a more direct and recommended approach. It makes the intention clearer, that is, 'to place these two strings side by side'.{{str1|add:str2}}Although it can achieve the same effect, butaddThe filter emphasizes the concept of 'addition', especially suitable when one or both values may be numbers, or when you want the filter to intelligently handle mixed types. When it is only for string concatenation, there is no essential difference in the final output, but it is written directly.{}It is more suitable for pure text concatenation.

3.addDoes the filter automatically add spaces or special characters when concatenating strings?

No.addThe filter will only concatenate the content of the two operands directly when concatenating strings, without automatically adding any additional spaces, connectors, or other special characters. If you need to include spaces, hyphens, or other characters in the concatenated result, you must explicitly include these characters as string literals in the operands, for example{{ "Hello"|add:" "|add:"World" }}.

Related articles

How to perform addition operations on numbers in AnQi CMS template, including integers and floating-point numbers?

In AnQiCMS template design, sometimes we need to perform dynamic calculations on the numbers displayed on the page, such as calculating the total price of goods, displaying the cumulative points of users, or adjusting certain values.Whether it is a simple integer addition or involves decimal floating-point arithmetic, AnQiCMS provides intuitive and powerful methods to meet these needs.This article will delve into how to implement addition operations in the AnQiCMS template, making your content display more dynamic and practical.

2025-11-08

How to get the last element/character of an array or string in Anqi CMS template?

In Anqi CMS template development, we often encounter the need to obtain the last element or character from a set of data (whether it is an array, list, or string).No matter whether it is to display the latest comments, the last item in the list, or extract the end information of specific text, understanding how to efficiently implement this at the template level will greatly enhance the flexibility and development efficiency of the template.The AnQi CMS template engine provides a simple and powerful filter function that can help us easily achieve this goal.

2025-11-08

How to get the first element/character of an array or string in AnQi CMS template?

During the development of website templates, you often encounter the need to extract the first element or character from a data collection (whether it is an array, slice, or string).AnQiCMS uses syntax similar to the Django template engine, providing rich tags (Tags) and filters (Filters), allowing us to flexibly and efficiently handle data.This article will introduce in detail how to use these powerful tools in the AnQiCMS template to easily achieve the operation of getting the first element/character of an array or string.--- ### One

2025-11-08

How to randomly select an element or character from an array or string in Anqi CMS template?

In Anqi CMS template, adding dynamism and fun to the content is an important aspect of improving user experience.Sometimes, we hope to display a random element on the page, such as a random slogan, a random recommendation tag, or randomly select a picture from a group of images.AnQi CMS relies on its flexible Django template engine syntax to provide a simple yet powerful way to meet this requirement, with the core tool being the `random` filter.

2025-11-08

How to set a default display value for possibly empty variables (such as arrays or strings) in Anqi CMS templates?

During the process of building a website with AnqiCMS, we often encounter such situations: a variable needs to be displayed in the template, but it may be empty for various reasons, such as not setting a thumbnail, a list without content, or optional information not filled in.If these empty variables are not processed, the page may appear with ugly blank areas, error messages, or layout errors, which undoubtedly affects the user experience.

2025-11-08

What is the difference between the `default_if_none` filter and the `default` filter in handling null values?

In the development of content management system templates, we often encounter situations where variable values are uncertain.Sometimes, the data may not have been filled in; sometimes, the data may exist, but its value is an empty string, zero, or a boolean false.To ensure the completeness and user experience of the website page display, it is particularly important to provide a friendly default display for these 'empty' values.

2025-11-08

How to dynamically generate filter conditions for content models in AnQi CMS templates (e.g., filtering by properties)?

When building and operating a website, providing users with an efficient content filtering function is crucial for improving user experience and content discoverability.AnQiCMS (AnQiCMS) leverages its flexible content model and powerful template tag system to help us easily implement dynamic generation of content model filtering conditions in templates, such as filtering by attributes. ### Content Model and Custom Fields: The Basis of Filtering One of the core strengths of AnQi CMS is its highly flexible content model.

2025-11-08

How does the `archiveFilters` tag display the filter list containing the 'All' option?

In website content operation, it is crucial to provide users with convenient and intuitive filtering functions.Especially when your website content structure is complex, containing various attributes and categories, a well-designed filter list can greatly enhance user experience, helping them quickly find the information they need.AnQi CMS provides a powerful `archiveFilters` tag, specifically designed to build this type of filter list based on document parameters.Today, we will delve into how to use this tag, especially how to cleverly add an 'All' option to make your filtering function more perfect and user-friendly.

2025-11-08