How to determine if a variable is empty in a template and set a default display value?

As an experienced Anqi CMS website operations personnel, I am well aware of the importance of the robustness of template content for website user experience and data display.In daily operations, we often encounter situations where variables may be empty. If not handled properly, it may lead to incomplete page display, or even cause the page to report errors.AnQiCMS (AnQiCMS) provides a flexible template engine with various ways to determine if a variable is empty and set a default display value, which is crucial for building high-quality, high-error-tolerant websites.

How to determine if a variable is empty in a template and set a default display value

In AnQi CMS template creation, when data or variables obtained from the background may not exist or be empty in some cases, we can use several methods to ensure the normal display of page content and avoid blank or error messages.The following will introduce several commonly used methods for judgment and setting default values.

One, use conditional judgment tags (if/else)

The template engine of Anqi CMS provides intuitive conditional judgment tags, among which{% if ... %}is the preferred way to judge whether a variable is empty or exists. When a variable isnil(undefined), empty string,falseor numbers0then,ifThe tag will treat it as a "false value".elsePart of the content.

For example, if we want to display the title of the articlearchive.TitleBut we worry that some articles may not have titles, and we can handle it like this:

<p>文章标题:{% if archive.Title %}{{ archive.Title }}{% else %}此文章暂无标题{% endif %}</p>

This code will check firstarchive.TitleDoes it exist or is it not empty. If true, then display its value;Otherwise, it will display 'This article has no title' as the default prompt.This method is suitable for scenarios where it is necessary to display completely different content blocks based on variable state.

Second, using filters (default/default_if_none) Set default values

In addition to condition judgment, Anqi CMS template also provides a simple filter function, which can set default values directly when outputting variables.

1.defaultFilter

defaultThe filter is set when the variable value is empty (includingnilis an empty string orfalseand0Provide an alternative value. This is the most commonly used way to set a default value, the code is very concise.

Suppose we need to display the description of the article.archive.DescriptionIf the description is empty, we hope to display 'No detailed description':

<p>文章描述:{{ archive.Description|default:"暂无详细描述" }}</p>

No matterarchive.DescriptionIsnilor it is an empty string, the above code ensures that an meaningful text is output.

2.default_if_noneFilter

In certain more refined scenarios, we may need to distinguish between a variable beingnil(undefined or not existing) or an explicit empty string or zero value.default_if_noneThe filter is specifically used for this purpose, it only provides a default value when the variable isniland does not replace empty strings,falseor0.

For example, ifarchive.Pricemay benilHowever0which is also a valid price (such as free), we can usedefault_if_none:

<p>商品价格:{{ archive.Price|default_if_none:"价格待定" }}</p>

Ifarchive.PriceIsnilIt will display "Price to be confirmed" ifarchive.PriceIs0It will display0This is very useful when it is necessary to retain explicit zero-value information.

3. Handling of empty collections in loop tags (for ... empty)

When processing list or array data, if the collection itself may be empty, the Anqi CMS template's{% for ... empty ... %}A structure provides an elegant solution to avoid blank pages on the page when there is no data.

For example, when we iterate over an article listarchivesifarchivesIf empty, we can display a friendly prompt:

<ul>
{% archiveList archives with type="list" categoryId="100" limit="10" %} {# 假设 categoryId 100 可能没有文章 #}
    {% for item in archives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <li>当前分类下没有任何文章。</li>
    {% endfor %}
{% endarchiveList %}
</ul>

WhenarchivesWhen the list contains data, it will traverse normally and display the article title; if the list is empty, it will execute{% empty %}Content within the block displays 'There are no articles under the current category.', thus maintaining the integrity of the page structure.

4. UsewithorsetTags define variables with default values

AlthoughwithandsetLabels are mainly used to define local variables or forincludeTag passing parameters, but in some cases, they can also be combined with filters to indirectly set default values for variables, so that they can be uniformly used in subsequent code blocks.

For example, we can first define a variable that may have a default value, and then reference it elsewhere in the template:

{% with displayed_logo = archive.Logo|default:"/static/images/default_logo.png" %}
    <img src="{{ displayed_logo }}" alt="网站Logo">
{% endwith %}

Or use:setThe scope of the tag is usually the current template file:

{% set displayed_banner = category.Banner|default:"/static/images/default_banner.jpg" %}
<div class="banner-area" style="background-image: url('{{ displayed_banner }}');"></div>

This method helps improve the readability and maintainability of the template, especially when a variable needs to go through multiple judgments or multiple references to default values.

By using these methods, we as the operators of AnQi CMS can ensure that even in cases where the data is incomplete or empty, the website pages can be presented in a friendly manner, greatly enhancing user experience and reducing potential errors.


Frequently Asked Questions (FAQ)

1.defaultFilters anddefault_if_noneWhat are the core differences between filters?

defaultFilters are when the variable value isnil(undefined), empty string (""), booleanfalseor numbers0will provide the default value set. Anddefault_if_noneThe filter is more strict, it only provides a default value when the variable isnil(undefined or does not exist), for empty strings,falseor0A clear "empty" value, it will retain the value of the variable itself. In short,default_if_noneMore suitable for scenarios where it is necessary to distinguish between "no data" and "data value is zero/empty".

Can I combine these judgment and default value setting methods on the same variable?

Yes, you can flexibly combine these methods according to your specific needs. For example, you can useiftags to judge a complex condition, and theniforelseuse them within a blockdefaultThe filter sets a default value for a child variable. Or, you can usesetSet a variable with a preset tag, whose value comes from adding another variable todefaultFilter. This combination can handle more complex logic, making the template stronger and more flexible.

3. How will it display on the page if I do not make any judgment or default value setting for a variable that may be empty?

In Anqi CMS template, if a variable does not exist or its value isnilIf you have not processed it, under normal circumstances, the template engine will render it as an empty string, which means nothing will be displayed on the page, leaving a blank area.This usually does not cause the page to crash, but it may cause the page layout to be incomplete or information to be missing, affecting user experience.Therefore, it is strongly recommended to always make appropriate judgments and default value settings for variables that may be empty.