How to display a default value when a variable is empty?

In website operation, 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 outputs a blank directly when displaying this content, it not only affects the aesthetics but may also confuse the user.At this moment, how to display a friendly default value when a variable is empty has become a very practical skill.

The AnQi CMS template system, 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 when variables 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 helpful assistant, when it detects that the variable you want to display is 'empty' - whether it isnila value, or an empty string""numbers0If it is an empty array or slice, it will automatically be replaced with the default value we set.

Its usage is very concise, just add the pipe symbol after the variable.|Then follow withdefaultAnd the default value you want to display, 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, you can provide a default value like this:

<img src="{{ archive.Logo }}" alt="{{ archive.ImageAlt|default:"网站图片" }}" />

For numeric variables such as the reading volume of an articlearchive.ViewsIf it may display as 0 or empty, we can alsodefaultoptimize the display through a

<span>阅读量:{{ archive.Views|default:"0" }}</span>

treat it differentlynilValue:default_if_noneFilter

In some specific scenarios, we may need to judge whether the variable is more accuratelynil(Similar to other programming languages in Go language,null). At this point,default_if_noneThe filter comes into play.

default_if_nonewithdefaultThe main difference is:defaultIt will check for various "empty" states including empty strings, 0, etc., whiledefault_if_noneonly when the variable is exactlynilIt will only display the default value. This means that if a variable is assigned an empty string"",default_if_noneit will retain this empty string, butdefaultit will display the default value.

For example, if we have a URL for a user avatar, but the URL field may not exist (asnil),while sometimes it may be an empty string (indicating that no avatar is set, but the field exists). In order tonilA default avatar is displayed at this time, while keeping the special handling of 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 benilIf it is empty, the default value is displayed directlydefaultThe filter is usually more convenient

Flexible applicationiflogical judgment

In addition to the filter, the Anqi CMS template is powerfulifThe logic label also provides more flexibility for handling variable null values. When we need to perform different logic based on whether a variable is empty or display more complex default content, ifTags are a good choice.

You can directly check a variable's 'truth value': when a variable exists and is not empty (such as not nil, not an empty string, not 0, etc.),{% if variable %}the condition is true. Otherwise,{% if not variable %}It is true.

Suppose we have a field for the article source.archive.SourceWe hope to display the source when there is a source, 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 way allows you to fully control the display logic when a variable is empty, and even nest more complex conditions.

The default value mechanism of the Anqi CMS backend custom field

It is worth mentioning that AnQi CMS inherently supports setting default values when customizing fields in the backend content model.This is a very convenient feature that can prepare for the situation where fields are empty in 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"), then when you publish an article in practice, if you do not fill in this "article author" field, the system will automatically fill in the default value you set when calling it on the front end. This means that for those fields that have already clarified the default display rules in the background, you even do not need to use it extra in the template.defaultThe filter will handle 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 indefaultorifJudgment still plays a role, providing finer control.

Summary and Practical Suggestions

Mastering these methods 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 fastest and most efficient choice.
  • when it is necessary to strictly distinguishnilfrom empty strings and to handle them differently,default_if_nonethe filter will be more accurate.
  • For complex logical judgments or when multiple content segments need to be displayed,ifthe logical judgment tag provides the greatest flexibility.
  • Do not forget to use the default value setting function directly in the Anqi CMS background content model, 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 your actual needs and team specifications. Maintaining clear and consistent template code will help with the long-term maintenance and iteration of the website.


Frequently Asked Questions (FAQ)

Q1:defaultanddefault_if_noneWhat are the specific differences between filters, and how should I choose?

A1:defaultFilters will display default values when variables are in the following 'empty' states:nil(null pointer), empty string""and a boolean valuefalsenumbers0and also empty sets (such as empty arrays, empty slices, empty maps). whereasdefault_if_nonethe filter is more strict, it only applies when the variable is exactlynilIt will display the default value only. This means that if a variable is an empty string"",default_if_noneIt will retain the display of an empty string, anddefaultit will be considered as "empty" and display the default value.

Q2: Why does the default value of the custom field I set 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 front end is not displaying as expected, there may be the following situations:

  1. The content manually filled in other values:If any non-empty value (even a space) is manually entered when adding or editing content, the default value set by the background will not take effect because the value manually entered in the content has higher priority.
  2. The string was manually filled in:If the field is manually cleared and saved as an empty string while editing the content""The default value on the back-end will not take effect (unless it is used extra in the template)defaultA filter is used to handle empty strings).
  3. Template tag call error:Make sure you have correctly called the custom field in the template. For example, if the custom field call field name ismyCustomFieldyou should use{{ archive.myCustomField }}or{% archiveDetail with name="myCustomField" %}to call.
  4. Field type mismatch:Check if the type of the custom field is compatible with the displayed content on the front end.

Q3: Besides an empty variable, what else can I use?defaultWhat 'empty' states does the filter handle?

A3:defaultThe filter is very versatile, it can handlenilvalues and empty strings, and can also deal with other types of 'empty' cases considered by the template system, including:

  • the number 0:For example{{ 0|default:"未指定" }}will display 'Not specified'.
  • Booleanfalse:For example{{ false|default:"不确定" }}It will display "uncertain."
  • Empty array, slice, or map:If a variable is an empty list([]) or an empty key-value pair set({})defaultIt will also be replaced with the default value. This is very useful to avoid displaying empty list structures on the frontend.