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

During the presentation of website content, we often encounter such situations: a variable may be empty due to missing data, the user not filling in, or other reasons.If these empty variables are output directly in the template, at best, blank spaces will appear on the page, affecting aesthetics. At worst, it may cause layout disorder, and even possibly expose unnecessary debugging information.It is particularly important to set a suitable default value for these variables that may be empty to ensure the completeness of the website content display and the smoothness of user experience.

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

ingeniously utilizedefaultFilter, set default value for variable

In the templates of AnQi CMS, the most direct and commonly used method is to usedefaultFilter. This filter can detect whether a variable is 'empty'——the 'empty' here usually refers tonilAn empty string"", or a number0or 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.

The usage is very intuitive:

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

For example, suppose we have a document title variablearchive.TitleIf it may 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", then the page will display "AnQi CMS Core Function"; ifarchive.Titleis an empty string, the page will display "No Title".

defaultFilter 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 representing the reading volumearchive.Viewscan be0We can also display it more friendly:

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

Deep understandingdefault_if_noneFilter to handle more precise null value judgment

Sometimes, our definition of 'empty' may be more strict, such as wanting to handle only those explicitly labeled asnil(null pointer) variables, and not empty strings, number 0 or booleanfalseConsidered as an empty value to be replaced. At this time,default_if_nonethe filter comes into play.

default_if_nonethe filter will only act on values that arenilthe variable to be replaced, without affecting the empty string"", or a number0or booleanfalseetc.nilthe value.

Its syntax usage isdefaultFilter similar:

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

For example, suppose we have a possible returnnilThe user nickname fielduser.NickName. If we want to displayuser.NickNameit isnilwhen it is""then it still displays an empty string (or no action is taken), thendefault_if_noneMore appropriate:

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

Ifuser.NickNameresponse fornilDisplay 'Anonymous user'; ifuser.NickNameresponse for""Display an empty string. This is very useful when distinguishing between 'non-existent' and 'exists but empty' states.

Use flexiblyifLabel, build more complex conditional logic

In some cases, simply replacing the default value may not meet the requirements.We may need to decide on displaying different HTML structures or executing more complex logic based on whether the variable exists.ifLogical judgment label becomes a powerful auxiliary tool.

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

The basic syntax structure is as follows:

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

CombineifLabel, we can achieve finer control. For example, ifarchive.Logoit exists, show the image; if it does not exist, then show 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,ifThe label provides greater flexibility because it is not just about replacing a value, but it can also change the entire structure of the output.

Practical suggestions and precautions.

  • choose the appropriate tool:For simple variable value replacement,defaultordefault_if_noneThe filter is**selection, which makes the code more concise. When it is necessary to display different HTML structures based on whether a variable exists,ifthe tag is more advantageous.
  • The default value of the background and template:In the background content model settings of AnQi CMS, some custom fields themselves can be set to default values (for example, the custom field settings mentioned in the "Content Model Usage Help"). The default values set in the background will take effect before the data is loaded into the template, which means that if the background has already set a default value for a field, this field in the template will already have the default value set by the background, even if it is not explicitly assigned.defaultFilter may not be necessary, ordefaultit will provide a secondary guarantee based on the default value in the background.
  • 保持代码可读性:try to make the template logic clear and easy to understand, avoid over-embedding complex.ifThe statement, if the logic is too complex, can consider data preprocessing at the controller layer.
  • Test:Before deployment, it is essential to thoroughly test variable values (empty, non-empty, different types, etc.) under various conditions to ensure the display meets expectations.

By mastering these methods, you will be able to control the display of the CMS website content more effectively, avoiding a decline in user experience due to missing data, making the website content more robust and user-friendly.


Common 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 willnilAn empty string"", or a number0and boolean valuesfalseare all considered empty values and replaced.default_if_noneThe filter will only be triggered when the value of the variable isnil(null pointer) is replaced, and for empty strings"", or a number0or a boolean valuefalseetc.nilthe value will not trigger the replacement. If you need to precisely distinguish between “variable does not exist” (nil) And "the variable exists but is empty" ("",0,false) Two cases, and for the former, the default value should be handleddefault_if_noneis a better choice; otherwise, usedefaultIt is usually enough, providing broader null value coverage.

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

A2: The template engine of Anqi CMS provides a more elegantfor...empty...endforstructure to handle this situation. Whenforthe list being traversed is empty,emptythe content within 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 better than usingif archivesand thenforLooping is more concise.

Q3: If a default value has already been set for the custom field in the background, it is still necessary to use it in the template.defaultFilter?

A3: Normally, if the background has already set a default value for the custom field and this default value meets your display requirements, then in the template,It is not necessaryit is not necessary to use anything extradefaultFilter.The default value set in the background will take effect before the data is loaded into the template, meaning that even if this field is not explicitly filled in the content, it already has a default value configured in the background in the template.defaultFilter as a secondary protection.