In the template world of AnQi CMS, we often encounter situations where variables may not have a value.For example, the nickname of the user may be empty, the introduction of the article may not be filled in, or a certain configuration item may not exist at all.At this time, in order to make the page display more friendly and information more complete, we need to set up a 'backup' for these variables - that is, default values.defaultanddefault_if_none.

As an experienced website operations expert, I know the importance of the robustness of variables in templates for content presentation.Today, let's delve deeply into these two filters that seem similar but actually have subtle and crucial differences in handling default variable values.Understanding the differences can help us control the display logic of page content more accurately and improve the user experience.

defaultFilter: Show action when the variable 'empty'

First, let's talk aboutdefaultFilter. Its design philosophy is very intuitive:The variable will display the default value set by you if it is considered "empty" by the template engine.The term "empty" here does not simply refer to the absence of a variable.

In the template context of AnQi CMS, a variable isdefaultconsidered as "empty" under the filter conditions including:

  • Variable isnil(or)None): This is the most common state of "no value".
  • The variable is an empty string""Even if the variable exists, but its content is empty,defaultit will also intervene.
  • The variable is a number0: For numeric types,0is also usually considered as a 'null' value.
  • The variable is a boolean valuefalse: Logical false values are also considered as “empty”.
  • The variable is an empty list or mapping (array or dictionary): If a collection type variable is empty,defaultit will also provide a default value.

Let's look at some actual examples, feel the taste ofdefaultwidespread applicability:

Suppose we have the following variable states:

  • user_name = "张三"
  • post_abstract = ""(Empty string)
  • view_count = 0(zero)
  • is_featured = false(Boolean false)
  • settings_value = nil(or the variable is not defined at all, the effect is equivalent to)nil)

Used in the templatedefaultFilter:

{{ user_name|default:"匿名用户" }}
{# 输出:张三 #}

{{ post_abstract|default:"暂无简介" }}
{# 输出:暂无简介 #}

{{ view_count|default:"0次阅读" }}
{# 输出:0次阅读 #}
{# 注意:如果想区分'0'和'未定义',这里可能不是**选择 #}

{{ is_featured|default:"不推荐" }}
{# 输出:不推荐 #}

{{ settings_value|default:"配置未设置" }}
{# 输出:配置未设置 #}

From these examples, it can be seen that,defaultThe filter is very accommodating when dealing with various "empty" values, acting like a diligent substitute player. As long as there is a vacant position on the field, whether the main player is absent or not in good condition, it will step in immediately.

default_if_noneFilter: Precisely identify the "no" value status

Next, we focus ondefault_if_noneFilter. WithdefaultDifferent from the broadness ofdefault_if_noneThe design philosophy isAccurately identify whether a variable isnil(i.e.,)None).

This means,default_if_noneOnly check whether a variable is in a state of "completely no value". If the variable exists, but its content is an empty string"", or a number0or a boolean valuefalse,default_if_noneIt will consider these as “having a value”, and will display the variable's actual value without applying a default.

We continue to use the variable state we just had, and seedefault_if_noneperformance:

{{ user_name|default_if_none:"匿名用户" }}
{# 输出:张三 #}

{{ post_abstract|default_if_none:"暂无简介" }}
{# 输出:(空字符串,不会显示"暂无简介") #}
{# 注意:这里与default过滤器行为不同! #}

{{ view_count|default_if_none:"未统计" }}
{# 输出:0 #}
{# 注意:这里与default过滤器行为不同! #}

{{ is_featured|default_if_none:"未知状态" }}
{# 输出:false #}
{# 注意:这里与default过滤器行为不同! #}

{{ settings_value|default_if_none:"配置未设置" }}
{# 输出:配置未设置 #}

By comparison, we can clearly seedefault_if_noneThe "rigornil.

实际应用场景:何时选择哪一个?

理解了它们的差异,选择合适的过滤器就变得简单而有策略了:

  • ChoosedefaultFilter:当你希望所有形式的“空”值(包括nil、空字符串、数字0、布尔false、空列表/映射)都能触发默认值时,defaultIs your first choice.For example, display the publication time of a blog post, if the article does not have an explicit publication time, you want to display 'Unknown publication date'; or an optional field, if nothing is filled in (including manually deleting it), a unified prompt is displayed.

  • Choosedefault_if_noneFilter:当你需要严格区分一个变量是“确实没有值”(nil)or 'intentionally set to a null value' (such as an empty string)""or numeric0){default_if_nonecan be used. For example, a product's price field, if the price is not setnil),显示“Price TBA”;但如果价格明确设置为0(表示免费),则直接显示0, rather than 'price to be determined'. For example, a user's personal signature, if the user has never set it (nil), it will show 'They are very mysterious'; if the user has set it but left it blank (""),then you may want the page to not display any signature, or display another piece of text to distinguish.

In short,defaultThe filter provides a more general and more fault-tolerant default value handling mechanism,default_if_nonethen provided a more precise and stricter 'existence or non-existence' judgment.As an operator of the AnQi CMS, flexibly using these two filters will make the display of your website content more logical and expressive, and reduce poor page experience caused by data loss.


Common Questions (FAQ)

  1. Q:defaultThe filter will treat numbers0or booleanfalseas "empty"? Answer:Yes, in the AnQi CMS template engine,defaultThe filter will treat numbers0、布尔falseAn empty string""andnilall are treated as "empty" values, and in this case, it displays the default value you set.

  2. 问:I hope that when the variable is an empty string""no content is displayed, but when the variable isnildisplay the default value "No data" what should I do? Answer:In this case, you need to usedefault_if_noneFilter. It will only act onnilthe value. If the variable is an empty string"",default_if_noneit will be considered as 'having a value', so the empty string will be displayed directly (i.e., no content will be displayed). For example:{{ variable|default_if_none:"暂无" }}.

  3. 问:这两个过滤器会改变变量的原始类型吗?例如,把nil变量设置为默认字符串后,它的类型就变成字符串了吗? Answer:No.defaultanddefault_if_noneFilter only affects the "display" mode of variables in the template.They are view layer logic processing and will not change the actual data type or value of the variables in the backend program.The variable retains its original type and value after being filtered in the template.