How to set a default friendly display value for a possibly empty variable in AnQiCMS template?

Calendar 👁️ 65

When building website templates, we often encounter situations where a variable may be empty in the template due to data not being entered, optional fields being left blank, or specific business logic.If these empty variables are not processed, the website front-end page may appear blank areas, display unfriendly placeholders, or even cause layout disorder, thereby affecting the user experience and the professionalism of the website.

Luckily, AnQiCMS provides two elegant and practical methods to help us set a default friendly display value for possibly empty variables in the template, ensuring the integrity and aesthetics of the website content.

1. UsedefaultFilter: The preferred option for simplicity and efficiency

When you want to directly display a preset text or image path when the variable is empty,defaultThe filter is the most direct and simplest choice. It can detect if a variable is empty (includingnilis an empty string orfalsesuch 'falsy' values), and if it is empty, it will output the default value you specified.

For example, if the "Contact Phone" field is not filled in on your website, the front-end may display a blank space. ThroughdefaultFilter, we can handle it like this:

Assuming you have passed.{% contact cellphone with name="Cellphone" %}Gained the contact information and assigned tocellphoneVariable.

<span>联系电话:{{ cellphone|default:"暂无联系电话" }}</span>

IfcellphoneA variable has a value (for example, “13888888888”), and the page will display “Contact phone: 13888888888”. IfcellphoneThe variable is empty, the page will display

For example, documents usually have thumbnails, but if some documents do not upload thumbnails, we do not want the page to show an icon indicating missing images. We can set a default image path:

<img src="{{ archiveThumb|default:"/public/static/images/default-thumb.png" }}" alt="文档缩略图"/>

HerearchiveThumbVariables may come from{% archiveDetail archiveThumb with name="Thumb" %}IfarchiveThumbIf valid, use it; otherwise, it will loaddefault-thumb.pngThis default image.

AnQiCMS also providesdefault_if_noneFilter. It isdefaultSimilar, but only for values ofnilThe condition takes effect, but will not handle empty strings orfalse. In most cases where a friendly default value is needed,defaultthe filter is sufficient to meet the needs.

2. CombinedifLabel for conditional judgment: An advanced customized solution

In some cases, simply replacing a default text is not enough, you may need to render a completely different HTML structure or perform more complex logic based on whether a variable exists. At this point,ifthe tag comes into play.

ifThe tag allows you to execute a code block when a variable exists (non-empty), or to execute another code block when the variable does not exist, or to perform no operation.

For example, a category page may have a Banner image, but not all categories do. If a Banner image exists, we want to display one<img>Label, if not exists, then display a piece of introduction text or a default background color block.

First, get the variable of the category Banner image:

{% categoryDetail categoryBanner with name="Logo" %}

Then, use it in the templateifLabel for judgment:

{% if categoryBanner %}
    <div class="category-banner">
        <img src="{{ categoryBanner }}" alt="分类Banner"/>
    </div>
{% else %}
    <div class="category-info">
        <h3>欢迎来到 {{ categoryTitle }} 页面</h3>
        <p>这里是分类的简介内容...</p>
    </div>
{% endif %}

In this way, you can design different display forms for the 'existence' and 'non-existence' of variables according to the actual situation, making the page more dynamic and user-friendly.

3. Advanced Application: Handling Content with HTML

When the default value you set or the variable itself may contain HTML code, in order to ensure that these HTML codes are correctly parsed by the browser and not displayed as plain text, you need to use|safeFilter. AnQiCMS template engine, for safety reasons, defaults to escaping all output content to prevent cross-site scripting (XSS) attacks.|safeThe filter explicitly tells the template engine that you are sure this content is safe and does not need to be escaped.

For example, the copyright information at the bottom of a website may include&copy;etc. HTML entities or<p>Label. If the copyright content may be empty, and you want to provide a default value containing HTML tags:

{% system siteCopyright with name="SiteCopyright" %}
<div class="footer-copyright">
    {{ siteCopyright|default:"&copy; AnQiCMS 版权所有. 保留所有权利."|safe }}
</div>

Here, |safeEnsured&copy;It can be correctly parsed as a copyright symbol, rather than being output as is. Similarly, ifsiteCopyrightthe variable itself contains<a>links or other HTML structures,|safeare also indispensable.

By flexible applicationdefaultFilters andifTags, combined with|safeThe filter processes HTML content, you can easily handle empty variables in the AnQiCMS template, thus building a stronger, better user experience website.


Frequently Asked Questions (FAQ)

Q1:defaultanddefault_if_noneWhat are the differences between filters?

A1:defaultThe filter is applied when the variable isnilan empty string""and a boolean valuefalseor numbers0or any 'falsy' value. While thedefault_if_nonefilter is more strict, it will only be applied when the variable's value isnil(which means that the default value is applied when undefined or NULL in the database) and will not process empty strings orfalseother false values. In most cases, usedefaultThe filter will be more universal and convenient.

Q2: Why do I sometimes need to add after the default value?|safe?

A2: AnQiCMS template engine, for website security, defaults to escaping all output variable content, converting<to&lt;,>to&gt;To prevent malicious script injection (XSS attacks). If the default value or variable you set itself contains legitimate HTML code (such as<p>这是一个段落</p>),and hope that these HTML codes can be parsed and displayed by the browser, rather than as plain text.|safeThe filter tells the template engine that this content is safe and does not need to be escaped.

Q3: Can I set a default value for a variable of list or array type? For example, when an image list is empty, can I display a default image?

A3: Yes.defaultThe filter applies to lists or arrays as well. If a list or array variable is empty (i.e., has a length of 0),defaultThe filter will directly output the default value you have set for it. However, it is important to note that if you still want the default value to be a list or array structure, you may need to combineifLabel judgment, or set the default value to an array string containing the default elements and cooperate|listFilter processing. But for the scenario of displaying a single default image, use it directly{{ item.Images|first|default:"/public/static/images/placeholder.png" }}orif item.ImagesLogic handling is more common in it.

Related articles

What is the correct syntax for using the `{{ obj|filter__name:param }}` filter in AnQiCMS templates?

AnQiCMS (AnQiCMS) provides strong support for content operations with its efficient and flexible features.In daily content display, we often need to process and format data in a fine-grained manner to ensure that information is presented to visitors in a **state**.At this moment, the 'filter' in the template has become an indispensable tool for us. Today, let's delve into the correct syntax for using filters in Anqi CMS templates: `{{ obj|filter_name:param }}`.Understand and master it

2025-11-07

How to quickly remove spaces or specific characters from both ends, left or right of a string in AnQiCMS template?

In content management, we often encounter situations where there are excessive spaces or unwanted specific characters at both ends of strings, which not only affects the display aesthetics of the content, but also sometimes causes unnecessary interference to data processing or search engine optimization (SEO).AnQiCMS uses a template engine syntax similar to Django, providing us with concise and efficient filters (Filters) to easily solve these problems.This article will introduce how to quickly remove spaces or specific characters from both ends, left, or right of a string in the AnQiCMS template.

2025-11-07

How to implement capitalizing the first letter of each word in the article title in AnQiCMS templates?

In website content operation, the standardization of article titles is often a key factor in improving the professionalism and user experience of the website.A neat and consistent title format not only makes the content more attractive but also helps improve the overall image of the website.AnqiCMS provides us with a very concise and efficient solution, which can easily capitalize the first letter of each word in the article title with a simple filter in the template.

2025-11-07

How to force all English text in the AnQiCMS backend custom fields to lowercase?

In website content operation, maintaining consistency in text format is a key step to improving user experience and SEO effects.Sometimes, we may encounter such a need: we hope that the English text input in the custom field of the background, regardless of how the user inputs it in uppercase or lowercase, can be forced to lowercase when displayed on the front-end.This not only makes the page look neater and professional, but also helps avoid SEO problems caused by inconsistent capitalization.

2025-11-07

How to format a 10-digit timestamp retrieved from the database into a custom date-time format in AnQiCMS template?

In website content display, we often encounter time data in a long string of numbers from the database, such as `1678886400`. This string of numbers, which is what we commonly call a timestamp, is very convenient for computers, but it seems cold and difficult to understand for users visiting websites.Fortunately, AnQi CMS provides us with a very convenient feature that can easily convert these original 10-digit timestamps into the date and time format we are accustomed to reading.

2025-11-07

What are the main differences between AnQiCMS's `date` and `stampToDate` filters when handling date data?

In AnQiCMS template development, displaying time data is an indispensable part, whether it is the publication time of articles, the update date of products, or the time records of user behavior, it needs to be presented to the user in a clear and readable manner.To meet the different time processing needs, AnQiCMS provides two core filters: `date` and `stampToDate`.

2025-11-07

How to always display product prices (floating point numbers) with two decimal places in AnQiCMS templates?

When operating a product display website, you may often encounter situations where you need to display product prices accurately.A professional and user-friendly website often requires a unified display format for product prices, such as always retaining two decimal places, even for integer prices, which are automatically filled with `.00`. AnQiCMS with its flexible template system makes these details handling very convenient.

2025-11-07

How does AnQiCMS automatically identify URLs or email addresses in text and convert them into clickable hyperlinks?

In the daily operation of websites, we often need to add various links in article content, such as URLs pointing to external resources, or email addresses for easy reader contact.Manually adding hyperlinks one by one is not only inefficient but also prone to errors.Fortunately, AnQiCMS provides very practical features that can intelligently identify URLs and email addresses in text and automatically convert them into clickable hyperlinks, greatly enhancing the efficiency and user experience of content editing.

2025-11-07