`add` filter combined with `default` filter to set default values for variables that may be empty before concatenation?

Calendar 👁️ 65

In the daily operation of Anqi CMS, we often need to concatenate the content of different fields to form a complete piece of information, such as generating a complete address or combining an attractive product title.However, a common challenge with dynamic content is that some variables may be empty.If concatenated directly, the blank content not only affects the appearance but may also lead to missing information or disordered format.

Fortunately, the powerful Django template engine syntax of AnQiCMS provides us with a flexible solution. By cleverly combiningaddFilters anddefaultThe filter allows us to set a 'backup' for variables that may be empty before content concatenation, ensuring that the output is always complete and friendly.

Next, let's take a look at how these two filters collaborate to help us build stronger and smarter template content.

addFilter: the master of content concatenation.

Get to know firstaddA filter, as the name implies, has the most intuitive function of performing addition. When applied to numbers, it will add two values like a plus sign in mathematics.

For example, if you have two numeric variablesnum1andnum2:

{% set num1 = 5 %}
{% set num2 = 2 %}
{{ num1|add:num2 }}  {# 结果是 7 #}

ButaddThe power of the filter goes far beyond this. It can also be used to concatenate strings! When you try to add a string to another value (whether it is a string or a number),addThe filter will very "intelligently" connect them together. It is not picky, and if it encounters a type that cannot be added directly (for example, adding a number to a non-numeric string), it will try to perform a type conversion.If the conversion fails, it will gracefully ignore the part that cannot be converted, ensuring that the template will not be interrupted.

For example, do you want to concatenate "Anqi" and "CMS":

{% set brand = "安企" %}
{% set product = "CMS" %}
{{ brand|add:product }} {# 结果是 安企CMS #}

Even:

{% set version = 2 %}
{{ "AnQiCMS v"|add:version }} {# 结果是 AnQiCMS v2 #}

defaultFilter: Guardian of missing values

UnderstoodaddAfter the ability to concatenate filters, we still need a partner to deal with the case where variables are empty, and that isdefaultFilter. When developing templates, when we obtain data from the backend database or API, some fields may not have values due to various reasons (such as users not filling in, data missing, etc.)At this time, if these empty variables are output directly, the page will be left blank or display unfriendlynull.

defaultThe filter acts as a 'backup plan': if the variable is empty (includingnilan empty string""and zero values), it will use the default value you specify instead.

For example, if you have auserNamevariable, but it may be empty:

{% set userName = "" %} {# 假设 userName 变量为空 #}
{{ userName|default:"匿名用户" }} {# 结果是 匿名用户 #}

{% set userName = "张三" %} {# 假设 userName 有值 #}
{{ userName|default:"匿名用户" }} {# 结果是 张三 #}

Strong combination: solve the pain point of splicing

Now, by combining these two filters, we can elegantly solve the problem of setting default values for possibly empty variables before concatenation.

Imagine that you are creating a contact information display for a product detail page, and you need to concatenate the phone number and email address.If a field is empty, we do not want it to display blank, but to give a hint.

The possible problems that may arise from direct concatenation:Assumearchive.PhoneIt is empty,archive.EmailHas value:

{{ "电话:"|add:archive.Phone|add:",邮箱:"|add:archive.Email }}
{# 结果可能是:电话:,邮箱:[email protected] #}

The comma directly following "Phone:" is very unprofessional.

CombinedefaultFilter solves:The correct practice is to check each variable that may be empty beforeaddUsing the filter, first,defaultThe filter sets a default value for it. So even if the original variable is empty,addThe filter always receives a valid string (i.e., the default value), thus ensuring the integrity of concatenation.

{% set archive = {Phone: "", Email: "[email protected]"} %} {# 模拟数据,电话为空 #}

{# 优雅拼接:为每个可能为空的变量设置默认值 #}
{{ "电话:"|add:archive.Phone|default:"未提供"|add:",邮箱:"|add:archive.Email|default:"未提供" }}
{# 结果是:电话:未提供,邮箱:[email protected] #}

The working principle here is:

  1. archive.PhoneIt is evaluated first because it is an empty string."".
  2. archive.Phone|default:"未提供"Convert empty string to"未提供".
  3. "电话:"|add:"未提供"Perform concatenation to get"电话:未提供".
  4. Then continue to concatenate",邮箱:"And then concatenatearchive.EmailBecause it has a value,defaultIt won't take effect).
  5. Finally, we get a complete and friendly string.

In this way, we can ensure that the final output to the user will always be well-formatted and complete text, regardless of whether the original data is missing.

Examples of actual application scenarios

This combination is very practical in AnQiCMS template creation, especially when dealing with various dynamic content:

  • Generate structured contact information:When you display company contact information at the bottom of the page, it is possible that not all of the phone, fax, email, etc. may be complete.

    {% set contactInfo = {Cellphone: "123-4567-8900", Fax: "", Email: "[email protected]"} %}
    <p>联系电话:{{ contactInfo.Cellphone|default:"暂无" }}</p>
    <p>传真:{{ contactInfo.Fax|default:"暂无" }}</p>
    <p>邮箱:{{ contactInfo.Email|default:"暂无" }}</p>
    {# 如果要拼接成一行: #}
    <p>联系方式:{{ contactInfo.Cellphone|default:"-"|add:" | "|add:contactInfo.Email|default:"-" }}</p>
    {# 结果:联系方式:123-4567-8900 | [email protected] #}
    
  • Build dynamic product descriptions or titles:Product properties may not be fixed, some may not have brands or models.

    {% set product = {Brand: "AnQi", Model: "", Color: "Black"} %}
    <h3>{{ product.Brand|default:"未知品牌"|add:" - "|add:product.Model|default:"通用型号"|add:" (颜色:"|add:product.Color|default:"不详"|add:")" }}</h3>
    {# 结果:AnQi - 通用型号 (颜色:Black) #}
    
  • Generate file path or URL:Some images or download links may be missing the specific directory name. “`twig {% set basePath = “https://en.anqicms.com/uploads/%}\n{% set year =

Related articles

How to dynamically generate a link to the comment area based on `item.Id` in `archiveList`?

In AnQi CMS, in order to enhance the user experience of the website, we often hope that users can quickly find the specific content on the page.For example, when you click on the "View Comments" link next to an article title on a document list page, you can directly jump to the comments section of the article detail page.This not only saves users time, but also makes interactions more direct. Today, let's discuss how to dynamically generate anchor links to comment sections in the `archiveList` loop based on the unique identifier `item.Id`.

2025-11-07

How to combine other filters with the `add` filter to ensure safe concatenation and prevent XSS attacks when processing user input?

In AnQi CMS, managing website content involves entering a variety of information regularly.Whether it is the main text of the article, user comments, or form submissions, this user-generated content injects vitality into the website while also bringing potential security risks, the most common and severe of which is XSS (Cross-site Scripting attack).This article will discuss how the `add` filter works in processing user input content, how it协同acts with other security filters to build a strong defense line, effectively preventing XSS attacks.

2025-11-07

How to use the `add` filter to dynamically add a uniform prefix or suffix to the single page titles in the `pageList`?

In Anqi CMS, content management is not limited to the backend's add, delete, modify, and query, but also manifests in the flexibility and diversity of front-end display.In the face of common single-page websites (such as "About Us", "Contact Us", etc.), sometimes we hope that they can be unified with specific identifiers when displayed in lists or navigation, such as If you modify the background title one by one, it is not only inefficient but also lacks uniformity and maintainability.At this time, utilizing the powerful template engine function of AnqiCMS, with the clever filter

2025-11-07

How does the `add` filter handle the addition/pasting operation with boolean values `true` and `false` as well as numbers or strings?

In Anqi CMS template development, we often need to process and display data.Among them, the `add` filter is a very practical tool that allows us to add numbers and concatenate strings.However, when the boolean values `true` and `false` are involved in these operations, their behavior may puzzle some users who are new to the subject.Today, let's take a deep dive into how the `add` filter handles addition or concatenation operations with boolean values, numbers, or strings.

2025-11-07

How to dynamically display

Display the record number at the bottom of the website, which is not only a requirement to comply with relevant laws and regulations, but also an important factor in enhancing the professionalism and user trust of the website.For users of AnQiCMS, dynamically displaying the filing number through the built-in powerful functions of the system is a very convenient operation, eliminating the need to frequently modify the code and greatly improving the maintenance efficiency of the website. ### Set the record number content in the background First, we need to set your website record number in the AnQi CMS background management interface. This is the basis of all dynamic display content, ensuring the accuracy of information

2025-11-07

Can the `add` filter be used to concatenate CSS style strings to implement dynamic inline styles?

AnQiCMS with its flexible and powerful template engine provides great convenience to users, allowing content presentation to be highly customized according to actual needs.In daily template development, we often encounter scenarios where we need to dynamically adjust the page display based on backend data, such as changing the title color based on the article reading volume, or displaying different background styles based on user permissions.At this point, we might wonder whether the built-in `add` filter of AnQiCMS templates can be used to concatenate CSS style strings to achieve these dynamic inline style controls

2025-11-07

How to dynamically add language parameters in the `add` filter of the `languages` tag that returns multilingual site links?

Under the flexible multi-language support of AnQiCMS, providing content to users worldwide has become very convenient.The system built-in `languages` tag can easily list all the language versions supported by your website and their corresponding links.However, in some scenarios, we may not only want to provide language switching functionality, but also dynamically add additional parameters to these multilingual links, such as for marketing tracking, A/B testing, or loading personalized content in specific languages.

2025-11-07

How to use the `add` filter to dynamically add navigation arrow symbols to the titles of `nextArchive` or `prevArchive`?

In website content operation, the subtle aspects of user experience often determine the overall effect.For the article detail page, if the "Previous" and "Next" navigation at the bottom of the page can be designed more intuitively, it will undoubtedly greatly improve the user's browsing efficiency and comfort level.This article will discuss how to utilize the powerful template function of Anqi CMS, especially the `add` filter, to dynamically add arrow symbols to these navigation titles, making them clear at a glance.Understand the requirement: Why to dynamically add navigation arrows?Imagine when the user has finished reading an excellent article

2025-11-07