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

Calendar 👁️ 84

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.

Related articles

How does AnQiCMS control the special display style of articles by setting the Flag attribute?

In Anqi CMS, the Flag attribute of the article is a very practical feature, which allows us to tag articles with special "labels" to display them uniquely on the website front-end.This mechanism greatly enhances the flexibility and diversity of content display, allowing website operators to easily control the display style and position of articles based on the importance, characteristics, or promotion needs of the content.What is the article Flag attribute? In simple terms, the Flag attribute is like a special "mark" that is attached to the article, it is not a category of the article

2025-11-07

How to automatically wrap long text for display in AnQiCMS templates?

During the operation of the AnQiCMS website, we often encounter scenarios where we need to display a large amount of text content, such as the main content of article detail pages, detailed descriptions of product introductions, or long introductions on category pages.These long texts, if not handled properly, may cause page layout to be disordered and affect the user's reading experience.Fortunately, AnQiCMS's powerful template engine provides various flexible ways to manage and display these long texts, including automatic line breaks and content truncation.AnQiCMS's template system has adopted the syntax of Django template engine, allowing us to use double curly braces

2025-11-07

How to automatically filter or process external links in AnQiCMS article content?

In daily website content operation, we often encounter situations where external links need to be cited in articles.These external links are handled well, they can enrich the content and provide references, but if not managed properly, they may also affect the SEO performance or user experience of the website.AnQiCMS is a content management system that focuses on efficiency and SEO, providing practical automated solutions in this aspect, helping us better manage external links in the article content.### Core options in the background content settings The core mechanism of AnQiCMS handling external links in articles

2025-11-07

How to truncate a string and add an ellipsis (...) in AnQiCMS templates?

In website content management, we often need to present a long text (such as an article abstract, product description) in a concise way on the page, which can not only save space but also improve the user's browsing efficiency.If the long text is not processed and displayed directly in the list, it may lead to a disorganized page and affect the user experience.The template engine of AnQiCMS (AnQiCMS) provides flexible and powerful filter (Filters) functionality, which can help us easily implement string truncation and automatically add ellipses.### AnQiCMS

2025-11-07

How to implement custom template file calling for category or article detail pages in AnQiCMS?

During the process of building a website with AnQiCMS, we often encounter such needs: we hope that a certain category list page or a unique article detail page has a layout and style that is different from the global unified default template.AnQiCMS is a content management system focused on flexibility and customization, providing a very convenient and powerful solution in this regard, allowing us to easily implement this fine-grained template calling.Implement custom template calling for category or article detail pages, AnQiCMS mainly provides two main methods

2025-11-07

How to format numbers in AnQiCMS templates, such as retaining decimal places?

In AnQiCMS template development, formatting numbers for display, especially controlling decimal places, is a very common requirement.No matter whether you want to display the price of products, the percentage in statistical data, or other values that need to be presented accurately, AnQiCMS's powerful template engine provides flexible filters (filters) to help you achieve these goals.

2025-11-07

How to automatically add watermarks to images in article content in AnQiCMS to protect copyright?

In today's era of increasingly rich digital content, the copyright protection of original images is particularly important.Whether it is a carefully photographed product image or an illustration drawn for an article, they all embody the creator's efforts and the brand image of the website.However, the situation where pictures are downloaded and used without permission is common, which not only violates copyright but may also dilute brand influence.Luckyly, AnQiCMS provides a convenient and efficient solution that helps us automatically add watermarks to images on the website, thereby effectively protecting original content.

2025-11-07

How to remove HTML tags in AnQiCMS template and display only plain text content?

When using AnQiCMS for content creation and display, we often need to flexibly control the presentation of content on the front end.Sometimes, the article or product description may contain rich HTML tags, which are used to provide beautiful layout on the detail page.

2025-11-07