How to use the `default` filter to set a default display value for possibly empty variables?

Calendar 81

In website content management, we often encounter a situation where a certain data variable may have no value on some pages or under certain conditions, that is, "empty" .If the template directly outputs these blank variables, ugly blank spaces will appear on the page, which not only affects the aesthetics but may also confuse the visitor.In order to avoid such embarrassment, Anqi CMS provides a very practical tool -defaultA filter that helps us set a graceful default display value for these possibly empty variables.

Why do we need to set a default display value for variables?

Imagine, your website displays a series of product information.Some products may not have uploaded thumbnails, some article authors may have chosen anonymous publication, and some contact information may be temporarily missing.If you directly call these variables in the template and they happen to be empty, the page will leave behind blank spaces, or display some unfriendly placeholders (such asnil/falseThis not only makes the website look unprofessional, but may also miss the opportunity to provide users with useful information.

defaultThe function of the filter is to solve such problems. It allows us to automatically replace it with a preset default value when the variable is empty, so that your website always maintains complete content and a smooth user experience.

UnderstanddefaultFilter: Say goodbye to blank content.

defaultThe filter is a very intuitive and powerful feature of Anqi CMS template engine. Its basic function is to output the default value we specify when a variable does not have a value.

Basic usage:

UsedefaultThe filter is very simple, just add a pipe symbol after the variable|anddefault:"默认显示内容"Just do it.

For example, if you have a variableuserNameIt may be empty, you can use it like this:

{{ userName|default:"匿名用户" }}

IfuserNameIf the variable has a value (such as "Zhang San"), then the page will display "Zhang San"; but ifuserNameit is empty, the page will display "Anonymous User".

defaultHow does the filter determine "empty"?

UnderstandingdefaultHow does the filter recognize 'empty'? It is very important in the Anqie CMS template environment,defaultThe filter will judge the following situations as 'empty':

  • in Go language,nilwhich is equivalent to in other programming languages,null)This is the most typical 'empty value'.
  • Empty string ("")Even if the variable exists, but its value is an empty string,defaultit will be considered as empty.
  • BooleanfalseIf the variable isfalse,defaultit will be considered as empty.
  • Number0If the variable is a number0,defaultit will be considered as empty.

Example:

{{ simple.nothing|default:"暂无数据" }}  {# 如果simple.nothing是nil,显示 "暂无数据" #}
{{ ""|default:"空字符串替代" }}           {# 如果变量是空字符串,显示 "空字符串替代" #}
{{ false|default:"不确定" }}             {# 如果变量是false,显示 "不确定" #}
{{ 0|default:"数量未知" }}               {# 如果变量是0,显示 "数量未知" #}
{{ 42|default:"默认值" }}                {# 42不是空,显示 42 #}
{{ "安企CMS"|default:"内容管理系统" }}    {# "安企CMS"不是空,显示 "安企CMS" #}

default_if_noneFilter: fornilprecise judgment

exceptdefault, Anqi CMS also providesdefault_if_noneFilter. This filter is more focused on determining whether the variable isnil(i.e., the true 'none'), and will not treat empty strings, boolean valuesfalseor numbers0as empty.

Basic usage:

{{ variable|default_if_none:"无" }}

default_if_noneJudging criteria:

  • Only when the variable isnilthen,default_if_nonethe default value will be applied.
  • If the variable is an empty string ("")、falseor0,default_if_noneit will retain its original value and will not use the default value.

Example:

{{ simple.nothing|default_if_none:"暂无数据" }} {# 如果simple.nothing是nil,显示 "暂无数据" #}
{{ ""|default_if_none:"空字符串替代" }}         {# 如果变量是空字符串,显示 "" (空字符串本身) #}
{{ false|default_if_none:"不确定" }}           {# 如果变量是false,显示 "false" #}
{{ 0|default_if_none:"数量未知" }}             {# 如果变量是0,显示 "0" #}

When to choosedefaultWhen to choosedefault_if_none?

  • If you wish to set a variablecompletely missing (nil), an empty string, andfalseor0When all display default values, then please usedefault. This is usually applicable to most scenarios and can more comprehensively cover various "no content" situations.
  • If you only want to display in variablesis indeednil(i.e. does not exist or is not assigned)then the default value is displayed, as well as empty strings,falseor0itself is valid information, thendefault_if_noneIt would be a more precise choice.

defaultactual application of filters

in the actual operation of website content,defaultThe filter can play a role in many places, making your website information display more flexible.

  1. Article or product title:When the article or product title is not filled in, a generic prompt can be displayed:

    <h1>{{ archive.Title|default:"【未命名】产品/文章" }}</h1>
    
  2. Thumbnail/Logo:If the thumbnail image of the article or product is not uploaded, a default image can be displayed:

    <img src="{{ archive.Thumb|default:"/static/images/default_thumb.jpg" }}" alt="{{ archive.Title|default:"默认图片" }}" />
    
  3. Contact Information:If contact information such as phone number, email, etc. is not set, 'None' or an alternative message can be displayed:

    <p>电话:{{ contact.Cellphone|default:"暂无联系方式" }}</p>
    <p>邮箱:{{ contact.Email|default:"请联系网站管理员获取" }}</p>
    
  4. Article description/summary:If the article does not have a description, it can be extracted from the text or a default prompt can be displayed:

    <p>{{ archive.Description|default:"这篇内容暂时没有简介,请点击查看详情。" }}</p>
    
  5. Custom field:For fields customized through the content model, such as "author", "source", etc., default values can also be easily set:

    <p>作者:{% archiveDetail author with name="author" %}{{ author|default:"佚名" }}</p>
    {# 或者如果是在遍历params时 #}
    {% archiveParams params %}
        {% for item in params %}
            {% if item.Name == "来源" %}
                <p>来源:{{ item.Value|default:"原创" }}</p>
            {% endif %}
        {% endfor %}
    {% endarchiveParams %}
    

With these simple applications, you will find that the page display of the website will become more robust and user-friendly, even if the data is incomplete, it can still be presented in a consistent and beautiful way.

Summary

defaultThe filter is an indispensable tool in the design of Anqi CMS templates.It can help us effectively handle various possible null value situations, ensuring the completeness and good display of website content, greatly enhancing the user experience and robustness of the template.flexibly usedefaultanddefault_if_noneIt will make your website content more flexible, avoid unnecessary blank spaces and errors, and thus provide a more professional browsing experience.

Frequently Asked Questions (FAQ)

1.defaultanddefault_if_noneWhat are the differences between filters?

defaultThe filter is applied when the variable isnil(an empty string,""), booleanfalseor numbers0will always apply the default value.default_if_noneThe filter is more strict, it will only apply the default value when the variable isnil(which is truly "none") and for empty strings,falseor0These "have values but are empty" cases, it retains the original value of the variable. In simple terms,defaultIt handles the "appears to be empty" cases more broadly, whiledefault_if_noneOnly handle cases where something truly does not exist.

2.defaultWhat values does the filter consider as blank to apply the default value?

defaultThe filter will consider the following types of variable values as blank:

  • in Go language,nil(i.e.),null)
  • Empty string ("")
  • Booleanfalse.
  • Integer0.
  • Floating point numbers0.0In these cases,defaultThe filter will use the default value you provided.

**3. I can use another variable from the template as `default

Related articles

How to use the `cut` or `removetags` filter to remove specific characters or HTML tags from strings in the AnQiCMS template?

In AnQi CMS template design, in order to better control the display of content, the system provides a variety of flexible filters (Filter).These filters can help you perform various string processing operations when outputting variables, such as removing specific characters or HTML tags, making the content neater and meeting your display requirements.Today, we will focus on the practical filters `cut` and `removetags`.

2025-11-07

How to convert a numeric string (such as "5.5") to a floating-point number or integer for display and calculation in AnQiCMS template?

In Anqi CMS template development, we often encounter scenarios where we need to handle numeric string.For example, the price stored in the background custom field may be a text type "5.5", or the numbers in the data obtained through the external API may exist as strings.At this point, if a direct numerical operation is performed, problems may arise.However, AnqiCMS's template engine provides very flexible and powerful functions, which can easily convert numeric strings to floating-point numbers or integers and perform subsequent display and calculation.

2025-11-07

How to use `truncatechars` or `truncatewords` filters to truncate long text or HTML content and add an ellipsis?

In website content management, we often encounter such situations: in order to maintain the neat and unified layout of the page, we need to truncate the long text content without destroying its semantics or layout.Whether it is an article summary, product introduction, or user comment, appropriately controlling the length of the text and adding ellipses can greatly enhance the user experience.The template engine of AnQiCMS provides us with two very practical filters: `truncatechars` and `truncatewords`, as well as their variants for handling HTML content

2025-11-07

How to use the `stampToDate` filter to format a timestamp into a readable date format in AnQiCMS template?

In AnQiCMS (AnQiCMS) template development, we often encounter the need to convert timestamp data stored on the back-end into a clear and readable date and time format on the user interface.The original timestamp, for example `1609470335`, has no meaning to ordinary users.In order to enhance the user experience of the website, it is particularly important to display time information appropriately.Luckyly, AnQiCMS provides a very practical built-in filter——`stampToDate`, which can help us easily achieve this goal.

2025-11-07

How to perform simple arithmetic operations (+ - * /) and display the results in AnQiCMS template?

In AnQiCMS templates, we often need to display website content and data.But sometimes, we not only need to display stored data, but also need to process this data in some simple ways, such as calculating the total price of goods, statistics page loading progress percentage, or adding a certain number of values, etc.

2025-11-07

How to configure the pseudo-static URL rule in AnQiCMS to optimize the display path and SEO friendliness?

In website operation, the URL is not only the address of the page content, but also an important part of search engine understanding, user identification, and brand building.A clear and meaningful URL structure, known as "pseudo-static" or "staticized" URL, is crucial for improving the SEO performance and user experience of a website.AnQiCMS is a content management system that focuses on SEO-friendliness and provides flexible and diverse static URL configuration features, helping us optimize the display path of content better.

2025-11-07

How to display the comment list of an article in AnQiCMS template, including multi-level replies and review status indicators?

In Anqi CMS, let your article page not only be a display of content, but also an active communication platform, and the comment feature is the bridge connecting content with readers.Understanding how to flexibly display an article's comment list in a template, including multi-level replies and clear review status indicators, is crucial for building an interactive website. ### The foundation of comment functionality: Ensure backend configuration is ready Before delving into template code, we first need to confirm that the comment feature is enabled in the AnQi CMS backend.

2025-11-07

How to retrieve and display custom fields in the AnQiCMS template for the website message form and ensure correct submission?

In Anqi CMS, adding and managing custom fields for the website's message form can not only help us collect more specific and targeted customer information, but also significantly enhance the interactivity and data collection efficiency of the website.AnQi CMS with its flexible content model and easy extensibility makes this process very convenient.This article will guide you on how to obtain and display custom fields in the Anqi CMS template and ensure that these fields are submitted correctly.### Step 1: Define the custom message field in the Anqi CMS backend First

2025-11-07