How to judge whether a variable is empty in a template and set a default display value?

As an experienced CMS website operation personnel in security, I know well the importance of template content robustness for website user experience and data display.In daily operation, we often encounter situations where variables may be empty. If not handled properly, it may result in incomplete page display or even page errors.The flexible template engine of AnQiCMS (AnQiCMS) provides multiple ways to determine if a variable is empty and set a default display value, which is crucial for us to build high-quality, high-error-tolerant websites.

How to judge whether a variable is empty in the template and set a default display value

In the template creation of AnQi CMS, when the 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.

一、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 the variable isnil(undefined)、empty string、falseor numeric0whenifLabels will treat it as a "false value" and executeelseof the content.

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

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

This code will check first:archive.TitleDoes it exist or not?If true, then display its value; otherwise, display 'This article has no title' as the default prompt.This method is suitable for scenarios where completely different content blocks need to be displayed based on the variable state.

Second, using filters (default/default_if_none) to set default values

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

1.defaultFilter

defaultWhen the variable value is empty (includingnil、empty string、falseand0Provide a fallback value. This is the most common way to set default values, and the code is very concise.

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

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

No matterarchive.DescriptionYesnilor it is an empty string, the above code will ensure that an meaningful text is output.

2.default_if_noneFilter

In some more refined scenarios, we may need to distinguish between a variable that isnil(undefined or does not exist) and an explicit empty string or zero value.default_if_noneFilter is specifically used for this purpose, it only provides a default value whennilis true, and does not replace empty strings,falseor0.

For example,archive.Pricecan benil? But0is also a valid price (e.g., free), we can usedefault_if_none:

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

Ifarchive.PriceYesnilIt will display “Price to be determined”archive.PriceYes0It will display0This is very useful when it is necessary to retain explicit zero value information.

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

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

For example, when we traverse a list of articlesarchivesifarchivesThe list is 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 and display the article title normally; if the list is empty, it will execute{% empty %}Block content, displaying “No articles under the current category.” to maintain the integrity of the page structure.

Four, usingwithorsetTag defines a variable with a default value

AlthoughwithandsetLabels are mainly used to define local variables or toincludeTags pass parameters, but they can also be indirectly used in conjunction with filters to set default variable values for unified use 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 usingsetTags, whose scope 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 templates, especially when a variable needs to go through multiple judgments or multiple references to default values.

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


Common Questions and Answers (FAQ)

1.defaultfilters anddefault_if_noneWhat is the core difference between filters?

defaultFilters when variable values arenil(undefined), empty string(""), booleanfalseor numeric0When, it will provide the default value set.default_if_noneThe filter is more strict, it only provides a default value whennilundefined or not existent, for empty strings,falseor0It retains the value of the variable itself, to put it simply,default_if_noneIt is more suitable for scenarios where it is necessary to distinguish between 'no data' and 'data value is zero/empty'.

2. Can I combine these conditional and default value setting methods on the same variable?

Yes, you can flexibly combine and use these methods according to specific needs. For example, you can useiftags to judge a complex condition, and theniforelseuse them within a block.defaultThe filter sets a default value for a sub-variable. Alternatively, you can usesetSet a variable with a predefined label whose value comes from another variable plusdefaultFilter. This combination can handle more complex logic, making the template more robust and flexible.

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

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