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

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