In the operation of a website, we often encounter such situations: a content field may not be filled in for various reasons, such as the author of the article, image description, or specific parameters of a product.If the template directly outputs a blank when displaying these contents, it not only affects the aesthetics but may also confuse the user.How to display a friendly default value when the variable is empty has become a very practical skill.
The template system of Anqi CMS, with its flexible and powerful features, provides us with various methods to elegantly solve this problem.It uses a syntax similar to the Django template engine, allowing us to easily display default values for variables when they are empty.
Smart usedefaultFilter
The most direct and most commonly used method in the Anqi CMS template is to usedefaultFilter. This filter acts like a caring assistant, when it detects that the variable you want to display is "empty"—whether it isnila value, an empty string"", or a number0When the array or slice is empty, it will be automatically replaced with the default value we set.
Its usage is very concise, you just need to add a pipe symbol after the variable.|Then followdefaultAnd display the default value you want, enclosed in double quotes. For example, if you want to display 'No Title' when the article title is empty, you can write it like this:
{{ archive.Title|default:"暂无标题" }}
Similarly, if there is a description field for an imagearchive.ImageAltit may be empty, and you can provide a default value like this:
<img src="{{ archive.Logo }}" alt="{{ archive.ImageAlt|default:"网站图片" }}" />
for numerical variables, such as the number of views of an articlearchive.ViewsIf it may display as 0 or empty, we can also optimize the display bydefaultusing a filter:
<span>阅读量:{{ archive.Views|default:"0" }}</span>
treat differentlynilValues:default_if_noneFilter
In certain specific scenarios, we may need to judge more accurately whether a variable isnil(Similar to other programming languages in Go language)null). At this point,default_if_noneThe filter comes into play.
default_if_noneWithdefaultthe main difference lies in:defaultIt will check for various "empty" states including empty strings, 0, and othersdefault_if_noneit will only display the default value if the variable is exactlynil. This means that if a variable is assigned an empty string"",default_if_noneThe empty string will be preserved, whiledefaultthe default value will be displayed.
For example, if we have a user avatar URL, but this URL field may sometimes not exist (it may be null or empty){nil),while sometimes it may be an empty string (indicating that no avatar is set but the field exists). In order to innilDisplays a default avatar when the time shows, while retaining special handling for empty strings, we can use it like this:
<img src="{{ user.AvatarURL|default_if_none:"/static/images/default_avatar.png" }}" alt="用户头像" />
If you want to use a variable regardless of its valuenilIf the value is still an empty string, display the default value directly, then usedefaultThe filter is usually more convenient.
Use flexiblyifLogical judgment
In addition to the filter, the strongifThe logic judgment tag also provides more flexibility for handling variable null values. When we need to execute different logic based on whether a variable is empty or display more complex default content, ifTags are a good choice.
You can directly check the 'truthiness' of a variable: when a variable exists and is not empty (such as non-nilnon-empty string, non-0etc.),{% if variable %}the condition is true. Otherwise,{% if not variable %}Then it is true.
Suppose we have a field for article sourcearchive.Source, we want to display the source when there is one, and display "Original from this site" when there is no source. At this point, combiningifandelsetags can be implemented in this way:
{% if archive.Source %}
<span>来源:{{ archive.Source }}</span>
{% else %}
<span>来源:本站原创</span>
{% endif %}
This allows you to fully control the display logic when a variable is empty, and even nested more complex conditions.
The default value mechanism for custom fields in the Anqi CMS backend
It is worth mentioning that the Anqi CMS supports setting default values when customizing fields in the background content model.This is a very convenient feature that can prepare for fields that may be empty during the content publishing process.
When you define a new field (such as 'Article Author') in the content model and set a default value (such as 'Anonymous User'), if you do not fill in the 'Article Author' field when publishing an article, the system will automatically fill in the default value it has set. This means that for fields that have already specified the default display rules in the background, you do not even need to use them in the template.defaultFilter it, the system will take care of everything for you.
However, if the content creator explicitly fills in an empty string in the background (for example, leaving the 'Article Author' field blank instead of not filling it in), and the front end needs a specific default display, then the template in thedefaultorifJudgment still plays a role, providing more refined control.
Summary and practical suggestions
Mastering the method of displaying default values when variables are empty can make your website template more robust and user-friendly.
- For simple default text or numbers,
defaultThe filter is the quickest and most efficient choice. - When it is necessary to strictly differentiate
nilAnd from an empty string, and to handle them differently based on thisdefault_if_noneThe filter will be more precise. - For complex logical judgments or when displaying multiple paragraphs of content,
iflogical judgment tags provide the greatest flexibility. - Do not forget to use the default value setting function directly in the content model of the Anqi CMS backend, which can simplify the complexity of the template from the source.
In practice, it is recommended that you choose the most suitable method based on actual needs and team specifications. Maintaining clear and consistent template code will help with the long-term maintenance and iteration of the website.
Common Questions and Answers (FAQ)
Q1:defaultanddefault_if_noneWhat are the specific differences between filters, and how should I choose?
A1:defaultFilters will display default values when the variables are in the following 'empty' states:nil(null pointer), empty string)"", boolean valuefalse, or a number0and empty collections (such as empty arrays, empty slices, empty maps). Anddefault_if_nonethe filter is more strict, it only applies when the variable is exactlynilThe default value is displayed only when time is specified. This means that if a variable is an empty string"",default_if_noneit will retain the display of an empty string, whiledefaultit will be considered as 'empty' and the default value will be displayed.
Q2: Why does the default value I set for the custom field in the Anqi CMS backend sometimes not display on the front end?
A2: If you have set a default value for a custom field in the backend content model but the frontend is not displaying it as expected, there may be the following situations:
- Content manually filled in other values:If any non-empty value (even a space) is manually entered in the field when adding or editing content, the default value set by the backend will not take effect because the manually input value in the content has higher priority.
- Content was manually filled with an empty string:If the field is manually cleared and saved as an empty string during content editing
""If so, the default value on the backend will not take effect (unless it is used additionally in the template).defaultFilter is used to handle empty strings). - Template tag call error:Ensure that you have correctly called this custom field in the template. For example, if the field name of the custom field being called is
myCustomFieldyou should use{{ archive.myCustomField }}or{% archiveDetail with name="myCustomField" %}to call it. - Field type mismatch:Check if the type of the custom field is compatible with the displayed content on the front end.
Q3: Besides empty variables, what else can I use?defaultWhat 'empty' states are handled by the filter?
A3:defaultThe filter is very versatile, it can handlenilvalues and empty strings, and can also deal with other various situations considered as "empty" by the template system, including:
- Number 0:For example
{{ 0|default:"未指定" }}It will display “Not specified”. - Boolean value
false:For example{{ false|default:"不确定" }}It will display “Indeterminate”. - Empty array, slice, or map:If a variable is an empty list (
[])or an empty key-value pair set{})defaultwill also be replaced with the default value. This is very useful for avoiding the display of an empty list structure on the frontend.