How to judge if a variable is empty in the template and display a default value?

During the presentation of web content, we often encounter such situations: a variable may be empty due to data loss, user non-filling, or other reasons.If you directly output these empty variables in the template, at best, blank spaces will appear on the page, affecting the aesthetics, and at worst, it may cause layout errors, even potentially exposing unnecessary debugging information.It is particularly important to set an appropriate default value for these variables that may be empty to ensure the completeness and smoothness of website content display and user experience.

The Anqi CMS uses a template engine syntax similar to Django, providing a concise and powerful tool for handling such issues.When you need to judge whether a variable is empty in a template and display a default value, you can flexibly use its built-in filters and logical judgment tags.

Skillfully usedefaultFilter, set a default value for the variable

In AnQi CMS templates, the most direct and commonly used method is to usedefaultA filter that can detect whether a variable is 'empty' - by 'empty' we usually meannilan empty string""numbers0or a boolean valuefalseOnce a variable is detected to be in one of these 'empty' states, it will automatically replace it with the default value we specify.

Its usage is very intuitive:

{{ 变量 | default:"默认值" }}

For example, suppose we have a document title variable.archive.TitleIf it might be empty, we can give it a default value like this:

<h1>{{ archive.Title | default:"暂无标题" }}</h1>

Ifarchive.TitleThe actual value is "AnQi CMS Core Function", so the page will display "AnQi CMS Core Function"; ifarchive.Titleis an empty string, the page will display "No Title".

defaultThe filter also applies to other types of data. For example, if the image addressarchive.Logois missing, we can display a placeholder:

<img src="{{ archive.Logo | default:"/static/images/default-logo.png" }}" alt="网站Logo">

or if a number represents the number of readsarchive.Viewsmay be0We can also give it a more friendly display:

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

Deep understandingdefault_if_noneFilter, handling more precise null value judgment

Sometimes, our definition of 'empty' may be more strict, such as only wanting to handle variables that are explicitlynil(null pointer), but not empty strings, the number 0, or booleanfalseAlso considered as an empty value. At this time,default_if_noneThe filter comes into play.

default_if_nonethe filter will only apply to values that arenilvariable replacement, which will not affect the empty string""numbers0or booleanfalseetc. nonnilthe value.

its syntax is similar todefaultthe filter is similar to:

{{ 变量 | default_if_none:"默认值" }}

For example, suppose we have a possible returnnilusername fielduser.NickName. If we want to display "Anonymous User" whenuser.NickNameit isniland it is just an empty string""If it still displays an empty string (or does nothing), thendefault_if_noneis more appropriate:

<span>昵称:{{ user.NickName | default_if_none:"匿名用户" }}</span>

Ifuser.NickNameWithniland shows "Anonymous user"; ifuser.NickNameWith""If it is empty, it will display an empty string. This is very useful when it is necessary to distinguish between 'not existing' and 'existing but empty' states.

Flexible applicationifLabel, to build more complex conditional logic.

Under certain circumstances, simply replacing the default value may not meet the needs.We may need to decide on displaying different HTML structures or executing more complex logic based on whether a variable exists.This is provided by Anqi CMS at this timeifLogic judgment tags become powerful auxiliary tools.

ifTags allow us to selectively render template content based on whether the condition is true (including whether the variable exists and is not empty).

The basic syntax structure is as follows:

{% if 变量 %}
    <!-- 变量存在且不为空时显示的内容 -->
{% else %}
    <!-- 变量不存在或为空时显示的内容 -->
{% endif %}

CombineifTags, we can achieve finer control. For example, ifarchive.Logoexists, display the image; if not, display a text prompt:

{% if archive.Logo %}
    <img src="{{ archive.Logo }}" alt="{{ archive.Title | default:"图片" }}">
{% else %}
    <p>该文档未上传封面图片。</p>
{% endif %}

For example, when dealing with custom fields, we may need to determine whether a specific field exists and has a value before deciding whether to display the entire information block:

{% archiveDetail customAuthor with name="author" %}
{% if customAuthor %}
    <p>作者:{{ customAuthor }}</p>
{% else %}
    <p>作者信息待补充。</p>
{% endif %}

In this case,ifLabels provide greater flexibility because they are not just replacing a value but can change the entire output structure.

Practical suggestions and precautions

  • Choose the right tool:For simple variable value replacement,defaultordefault_if_noneFilters are **choices, they make code more concise. And when you need to display different HTML structures based on whether a variable exists,iftags are more advantageous.
  • Back-end default value and template default value:In the AnQi CMS backend content model settings, some custom fields can be set to default values (for example, the custom field settings mentioned in the "Content Model Usage Help"). The default values set by the backend will take effect before the data is loaded into the template, which means that if the backend has already set a default value for a field, then this field in the template, even if it is not explicitly assigned, has already possessed the default value set by the backend, and at this time, you can usedefaultFilter may not be necessary, or perhapsdefaultWill provide a second guarantee based on the default value in the background.
  • Keep the code readability:Try to make the template logic clear and easy to understand, avoid overly complex nesting.ifIf the logic is too complex, consider preprocessing the data at the controller layer.
  • Test:Before deployment, it is essential to thoroughly test variable values (empty, non-empty, different types, etc.) to ensure the display meets expectations.

By mastering these methods, you will be able to control the display of content on the Anqi CMS website more effectively, avoid the decline in user experience caused by missing data, and make the website content stronger and friendlier.


Frequently Asked Questions (FAQ)

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

A1: The main difference lies in their definition of 'empty'.defaultThe filter will also treatnilan empty string""numbers0and boolean valuesfalseBoth are considered empty values and are replaced.default_if_noneThe filter will only replace when the variable value isnil(null pointer) for empty strings, the value of empty strings will not trigger the replacement. If you need to distinguish exactly “variable does not exist” (""numbers0or a boolean valuefalseetc. nonnilThe value will not trigger replacement. If you need to distinguish precisely between 'variable does not exist' (nil) And the variable exists but is empty ("",0,falseThen, use the default valuedefault_if_noneIs a better choice; otherwise, usedefaultIt is usually enough, it provides broader null value coverage.

Q2: How to determine if a list (for examplearchiveListreturnedarchives) is empty and display 'No content'?

A2: The template engine of Anqi CMS provides a more elegant structure for list loops.for...empty...endforThis structure is used to handle this situation. Whenforthe list being traversed by a loop is empty,emptythe content inside the block will be rendered.

Example:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <!-- 列表有内容时显示每个项目 -->
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <!-- 列表为空时显示的内容 -->
        <li>暂无内容</li>
    {% endfor %}
{% endarchiveList %}

This method is more concise than usingif archivesand thenforthe loop is more concise.

Q3: If the backend has already set a default value for the custom field, it still needs to be used in the templatedefaultfilter?

A3: In most cases, if the background has already set a default value for the custom field and this default value can meet your display requirements, then in the templateNot requiredadditional usedefaultFilter. The default value set in the background will take effect before the data is loaded into the template, meaning that even if the field is not explicitly filled in the content, it already has a default value configured in the background in the template.However, in some special scenarios, for example, if you want to provide an 'ultimate fallback' default value on top of the background default value (when the background default value is still not ideal), or if you want to override the background default value in certain specific templates, then you can still usedefaultThe filter acts as a secondary safeguard.