defaultanddefault_if_noneTwo filters come in handy. They both provide default values for variables, but there are subtle and important differences in the criteria for determining 'empty'.
defaultFilter: Flexible 'null' handling
defaultFilter is a relatively "tolerant" default value setting tool. Its design philosophy is: as long as the variable looks "empty", apply the default value. Specifically,defaultauto judge the following situations as “empty”:“
- the variable does not exist or is
nil(no value):if the variable does not exist in the template context or is explicitly set tonil. - Empty string
"":The value of the variable is an empty string with no characters. - Number
0:The value of the variable is the number zero. - Boolean value
false:The value of the variable is a boolean false. - Empty array, empty slice, or empty map:If the variable is of a collection type but contains no elements.
Therefore, when you want any form of "content missing" to be replaced by a default value,defaultFilter is your preferred choice. It can conveniently provide a fallback solution for users, avoiding unnecessary blank spaces or incomplete information on the page.
Example of applicable scenarios:
- Article title or summary:If the editor forgets to fill in the article title or summary, 'No title' or 'No summary available' can be displayed.
{{ article.Title|default:"无标题" }} {{ article.Description|default:"暂无简介" }} - Product price:)If the product is not priced, display 'Price to be discussed.'
{{ product.Price|default:"价格待议" }} - Username:If the user has not set a nickname, display 'Anonymous user.'
{{ user.Nickname|default:"匿名用户" }}
default_if_noneFilter: Precise 'No value' judgment
WithdefaultThe inclusiveness of the filter varies,default_if_noneWhen the filter determines whether a default value needs to be applied to a variable, it is more 'rigorous'. It only focuses on one case: whether the variable isnil(or in the Go language,nilwhich means that the variable has not been assigned or points to any content)。
this means that for an empty string"", or a number0or a boolean valuefalse,default_if_noneThe filter will consider them to be valid values and will output them as is without applying any default values. Only when the variable is explicitly set will it intervene and provide default content.nilThen it will介入 and provide default content.
Example of applicable scenarios:
- Optional image link:Assume a product image variable
product.ImageUrlIf this image is not set in the database, its value may benil. But if it is set, even if it is an empty string"", it may also represent the intentional non-display of images.
In this example, if{{ product.ImageUrl|default_if_none:"/static/images/placeholder.webp" }}product.ImageUrlYesnil; it will display a placeholder if it is an empty string""If it is set to auto, it will display an empty string (the browser will consider the image address to be empty and not load the image), which may be the behavior we want. - Stock quantity:If the stock quantity of a product is
product.StockYes0This usually represents a meaningful value (indicating sold out), not "no inventory information." Only when the inventory information is completely missing (nilWhen it is shown, the default prompts such as "Inventory sufficient" will be displayed.
If{{ product.Stock|default_if_none:"库存充足" }}product.StockYes0will be displayed on the page.0;如果是Englishnilwill be displayed as "Inventory sufficient."
The core differences and selection criteria
In simple terms, the core difference between these two filters lies in their definition of 'empty':
defaultThe definition of 'empty' for the filter is broader, covering:nil、empty string、0、falseand other situations.default_if_noneFilter definition for "empty" is stricter, only fornil(no value) situations.
In the actual template development, we recommend that you choose an appropriate filter based on the specific meaning of the variable and the behavior you wish to display when content is missing:
- Choose
default:when you encounter most common text content (such as article titles, descriptions, common fields), tend to usedefaultIt can provide the most common default value guarantee to ensure that the page displays friendly when the information is incomplete. - Choose
default_if_none:When0/falseor an empty string""It is meaningful business data. You want them to be displayed accurately when they exist, rather than being overwritten by default valuesdefault_if_none. For example, product inventory is0Status isfalseOr the image link is intentionally left blank"".
Understanding the difference between these two will enable you to control the data display logic in the security CMS template more precisely, enhancing the robustness and user experience of the website. In the development process, it's a good idea to first usedefaultTry it out, if you find0or""incorrectly replaced, consider switching todefault_if_if_nonefor more precise control.
Common Questions (FAQ)
Q1: Why is my article abstract field empty, {{ archive.Description|default_if_none:"暂无简介" }}Does not display the default value?
A1: This is becausearchive.DescriptionThe value is very likely an empty string"",instead ofnil.default_if_noneThe filter will treat an empty string as a valid value and will not apply the default value. If you want to display the default value in this case, you should usedefaultFilter:{{ archive.Description|default:"暂无简介" }}.
Q2: Can I use these filters to set default values for a complex object (such as a struct)?
A2: These two filters are mainly used to handle the default values of a single variable or variable attribute. If you try to use it on a complete complex object (such as{{ article|default:"没有文章信息" }}), it is usually only when thisarticleThe object itself isnilwill take effect. A more common practice is, you should handle theindividual propertiesUse these filters to ensure that each potentially empty field has a default display. For example,{{ article.Title|default:"无标题" }}and{{ article.Author|default:"佚名" }}.
Q3: Besides these two filters, are there other methods to handle empty variables in templates?
A3: Of course. The most basic and direct way is to useifLogical judgment tag:
{% if article.Description %}
{{ article.Description }}
{% else %}
暂无简介
{% endif %}
In addition, for lists that need to be traversed in a loop, you can usefor emptystructure, and display specific content when the list is empty:
{% for item in newsList %}
<!-- 显示新闻内容 -->
{% empty %}
目前没有最新新闻
{% endfor %}
These methods provide more flexible control and can choose the most suitable processing method according to different business logic.