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:
archive.PhoneIt is evaluated first because it is an empty string."".archive.Phone|default:"未提供"Convert empty string to"未提供"."电话:"|add:"未提供"Perform concatenation to get"电话:未提供".- Then continue to concatenate
",邮箱:"And then concatenatearchive.EmailBecause it has a value,defaultIt won't take effect). - 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 =