How to set a default display value for possibly empty variables (such as arrays or strings) in Anqi CMS templates?

Calendar 👁️ 57

During the process of building a website with AnqiCMS, we often encounter such situations: a variable needs to be displayed in the template, but it may be empty for various reasons, such as not setting a thumbnail, a list without content, or optional information not filled in.If these empty variables are not processed, the page may display ugly blank areas, error messages, or misaligned layout, which undoubtedly affects the user experience.

AnqiCMS's powerful template engine provides various mechanisms to elegantly handle these potentially empty variables, ensuring that the website maintains good display effects and user experience even in cases of incomplete data.We will discuss several practical strategies in detail.

Handle empty arrays or lists:{% for ... empty %}The Art of Elegance

When you need to loop through a list in a template (such as an article list, image gallery, etc.), but are not sure if the list will always have content, in the AnqiCMS template engine,{% for ... empty %}Structure is your powerful assistant. It allows you toforhandle data normally within a loop, and at the same timeemptydefine the content to be displayed when the list is empty.

For example, on a category page, it is necessary to display a list of articles, but there may be no articles under this category:

{# 假设 archives 是一个可能为空的文章列表 #}
<div>
    {% archiveList archives with type="page" limit="10" %}
        {% for item in archives %}
        <div class="article-item">
            <a href="{{item.Link}}">
                <h5>{{item.Title}}</h5>
                <div>{{item.Description}}</div>
            </a>
        </div>
        {% empty %}
        <div class="no-content-message">
            抱歉,当前分类下暂无文章。
        </div>
        {% endfor %}
    {% endarchiveList %}
</div>

In this example, ifarchivesThe list has content, the system will normally render the title and description of each article. But ifarchivesIt is empty,{% empty %}The text

Handle empty strings or single values:defaultThe wonder of filters

For a single variable (such as a string, number, or object property), if it may be empty or undefined, usedefaultA filter is a concise and efficient method. This filter provides a default value for display when the variable value is empty or undefined.

For example, you want to display the filing number of the website, but the background may not be filled in, or the thumbnail of an article may not exist:

{# 显示网站备案号,如果为空则显示“暂无备案信息” #}
<p><a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">{% system with name="SiteIcp" %}{% else %}{{'暂无备案信息'}}</a> &copy;2021 AnQiCMS. All Rights Reserved</p>

The better way to do it is to use a filter:{{ variable|default:"默认值" }}

For example, when you need to display a thumbnail of an article, but some articles may not have uploaded a thumbnail:

<img src="{{ item.Thumb|default:'/static/images/default-thumb.jpg' }}" alt="{{ item.Title|default:'无标题文章' }}" />

Here, ifitem.Thumbis empty, the image will display as/static/images/default-thumb.jpgthis default image; ifitem.TitleIt is empty,altThe attribute will display “No Title Article”.

It is worth mentioning that the AnqiCMS template engine also providesdefault_if_nonefilter.defaultThe filter will treat empty strings, the number 0, and boolean valuesfalseas well asnil(Null pointer) are treated as empty. Anddefault_if_nonethen only fornilThe value is effective. In the Go language template environment, this can more accurately handle the case where the data is a null pointer rather than an empty string. Generally speaking,defaultThe filter is sufficient to handle most scenarios.

Masterfully control the display logic:{% if ... %}Conditional judgment

Besides the aforementioned methods of setting default values,{% if ... %}Conditional tags provide finer control.You can check if a variable exists, whether it is non-empty, even perform more complex logical judgments, thus deciding whether to display an element or display some alternative content.

For example, a page may have a canonical link (Canonical URL), but not all pages need to be set, or only displayed when set<link>Tags:

{%- tdk canonical with name="CanonicalUrl" %}
{%- if canonical %}
<link rel="canonical" href="{{canonical}}" />
{%- endif %}

Here, {%- if canonical %}Will checkcanonicalDoes the variable have a value. Ifcanonicalis empty, the whole<link>The tag will not be rendered on the page. This method is very useful in handling some SEO tags that may not exist, optional social sharing buttons, and other scenarios.

For example, you want to display the tags of an article, but some articles may not have tags:

{% tagList tags with itemId=item.Id limit="10" %}
    {% if tags %} {# 检查 tags 列表是否非空 #}
        <div class="article-tags">
            标签:
            {% for tag in tags %}
            <a href="{{tag.Link}}">{{tag.Title}}</a>
            {% endfor %}
        </div>
    {% endif %}
{% endtagList %}

Comprehensive application, create a robust template

In actual template development, these methods can be flexibly combined according to specific requirements. You can first use{% if %}Determine whether a large block contains content, if not, the entire block does not display; within the block with content, for individual variables that may be empty, usedefaultFilter default settings; for lists that may be empty, use{% for ... empty %}the structure.

By these strategies, your AnqiCMS website template will become more robust, whether the data is complete or incomplete, it can present to the user in an elegant and friendly manner, greatly enhancing the usability and professionalism of the website.


Frequently Asked Questions (FAQ)

1.defaultFilters anddefault_if_noneWhat are the differences between filters in AnqiCMS templates? defaultFilters check if a variable is an empty value (including empty strings, number 0, boolean value)falseas well asnil/nullIf it is empty, use the default value you provided.default_if_noneIt is more strict, it will only occur when the variable is.nilWhen a null pointer is used, the default value is used. For empty strings, numbers 0, and other cases where there is a 'value' but it is 'empty', it will not trigger the default value.In the AnqiCMS Go language backend environment, understanding this helps to handle data types more accurately.

2. Why does my{% for ... empty %}The code has not taken effect, and the list is still blank when it is empty.This usually has several reasons. First, make sure that yourforloop variable is indeed an array, slice, or an iterable object. If it is a single value,emptyThe block will not be triggered. Next, check the one you pass toforDoes the loop variable really contain nothing? Sometimes, a variable may contain an empty object instead of an empty array, or it may be nothing itself.nilIn this case,forthe loop may skip it directly without entering.emptyblock. In these cases, you may need to{% for %}use the tag outside first{% if %}to make a more comprehensive judgment of the variable.

3. How to set the default display value for custom model fields in the background?AnqiCMS allows you to set default values for fields when customizing content models (as mentioned in the "Content Model Help" document).If the backend has already set a default value for a custom field, you can directly call the field in the template, and the system will automatically use the default value set by the backend.defaultFilter, for example{{ item.custom_field|default:'这里是自定义字段的默认值' }}.

Related articles

How does the `add` filter handle string concatenation operations?

When developing templates with Anqi CMS, we often encounter scenarios where we need to combine text fragments or numbers for display.Whether it is to build dynamic page titles, concatenate URLs, or perform simple numerical calculations on the page, flexible data processing capabilities are crucial.The Anqi CMS template engine provides a very practical tool - the `add` filter, which can help us easily achieve string concatenation and numeric addition operations.What is the `add` filter?

2025-11-08

How to perform addition operations on numbers in AnQi CMS template, including integers and floating-point numbers?

In AnQiCMS template design, sometimes we need to perform dynamic calculations on the numbers displayed on the page, such as calculating the total price of goods, displaying the cumulative points of users, or adjusting certain values.Whether it is a simple integer addition or involves decimal floating-point arithmetic, AnQiCMS provides intuitive and powerful methods to meet these needs.This article will delve into how to implement addition operations in the AnQiCMS template, making your content display more dynamic and practical.

2025-11-08

How to get the last element/character of an array or string in Anqi CMS template?

In Anqi CMS template development, we often encounter the need to obtain the last element or character from a set of data (whether it is an array, list, or string).No matter whether it is to display the latest comments, the last item in the list, or extract the end information of specific text, understanding how to efficiently implement this at the template level will greatly enhance the flexibility and development efficiency of the template.The AnQi CMS template engine provides a simple and powerful filter function that can help us easily achieve this goal.

2025-11-08

How to get the first element/character of an array or string in AnQi CMS template?

During the development of website templates, you often encounter the need to extract the first element or character from a data collection (whether it is an array, slice, or string).AnQiCMS uses syntax similar to the Django template engine, providing rich tags (Tags) and filters (Filters), allowing us to flexibly and efficiently handle data.This article will introduce in detail how to use these powerful tools in the AnQiCMS template to easily achieve the operation of getting the first element/character of an array or string.--- ### One

2025-11-08

What is the difference between the `default_if_none` filter and the `default` filter in handling null values?

In the development of content management system templates, we often encounter situations where variable values are uncertain.Sometimes, the data may not have been filled in; sometimes, the data may exist, but its value is an empty string, zero, or a boolean false.To ensure the completeness and user experience of the website page display, it is particularly important to provide a friendly default display for these 'empty' values.

2025-11-08

How to dynamically generate filter conditions for content models in AnQi CMS templates (e.g., filtering by properties)?

When building and operating a website, providing users with an efficient content filtering function is crucial for improving user experience and content discoverability.AnQiCMS (AnQiCMS) leverages its flexible content model and powerful template tag system to help us easily implement dynamic generation of content model filtering conditions in templates, such as filtering by attributes. ### Content Model and Custom Fields: The Basis of Filtering One of the core strengths of AnQi CMS is its highly flexible content model.

2025-11-08

How does the `archiveFilters` tag display the filter list containing the 'All' option?

In website content operation, it is crucial to provide users with convenient and intuitive filtering functions.Especially when your website content structure is complex, containing various attributes and categories, a well-designed filter list can greatly enhance user experience, helping them quickly find the information they need.AnQi CMS provides a powerful `archiveFilters` tag, specifically designed to build this type of filter list based on document parameters.Today, we will delve into how to use this tag, especially how to cleverly add an 'All' option to make your filtering function more perfect and user-friendly.

2025-11-08

How to loop through a document list in an Anqi CMS template and output custom parameters for each document?

AnQiCMS provides powerful template customization capabilities, allowing us to flexibly display various content according to the actual needs of the website.When we not only need to loop through the document list but also want to output unique custom parameters for each document, the template tags of AnQiCMS can well help us achieve this.This is particularly important for a content model that has diversified attributes for displaying product details, real estate information, job openings, etc.

2025-11-08