How to set a default display value for a possibly empty variable, string, or object?

Calendar 👁️ 63

In website content management, data integrity and consistency are crucial.However, in actual operation, we often encounter situations where certain variables, strings, or objects may be empty.If the template does not handle these null values properly, the front-end page may appear blank, disordered, or even crash, severely affecting user experience.AnQiCMS (AnQiCMS) provides a variety of flexible and powerful template tags and filters to help us elegantly handle potential null values, ensuring the stability and beauty of the website content.

The AnqiCMS template system has adopted the Django syntax, it provides a series of intuitive tools to set default display values, so that even empty areas can be displayed properly, thereby enhancing the professionalism and customer satisfaction of the website.

Core Strategy One: Skillfully Use Default Value Filters

In the AnQi CMS template,defaultA filter is a very practical tool that allows us to set a backup value for variables that may be empty or undefined. When the value of the variable isfalse/0an empty string""or an empty listdefaultthe filter will come in handy.

for example, if your article title variableitem.TitleSometimes it may be empty, you do not want to have a blank space on the page, but instead display a default prompt, you can use it like this:{{ item.Title|default:"无标题内容" }}So, even ifitem.TitleEmpty, the page will also display 'No title content'.

Another closely related filter isdefault_if_none. It is withdefaultSimilar, but more focused on processingnil(i.e., in Go language)null). In some cases, variables may be explicitly set tonilIt is not an empty string or zero. At this point,default_if_noneit ensures that you set a fallback value.{{ someVariable|default_if_none:"N/A" }}This filter is particularly effective in handling potentially empty fields retrieved from the database, as it helps ensure that the page displays friendly and complete information.

Core Strategy Two: Use conditional judgment to achieve flexible control

When you need to decide on different content structures to display based on whether a variable exists or is empty,ifLogic judgment tags become your powerful assistant. It allows you to write more complex conditional logic to meet diverse display requirements.

For example, when displaying a thumbnail of an article or category, you may want to show it only when the image actually exists.<img>Tag, otherwise do not display, or display a placeholder image:

{% if item.Thumb %}
  <a href="{{ item.Link }}">
    <img src="{{ item.Thumb }}" alt="{{ item.Title|default:'图片' }}">
  </a>
{% else %}
  {# 如果没有缩略图,可以显示一张默认的占位图 #}
  <a href="{{ item.Link }}">
    <img src="/static/images/default-thumb.png" alt="{{ item.Title|default:'默认图片' }}">
  </a>
{% endif %}

By{% if ... %}and{% else %}Structure, you can provide multiple guarantees for the content to ensure that the page can present elegantly regardless of the data status.

Core Strategy Three: The elegant way to handle empty lists.

When displaying article lists, comment lists, or friend links and other content, data is usually provided in the form of arrays or slices.If these lists happen to be empty, directly traversing them may cause the page to be blank.AnQi CMS offorA loop tag provides a{% empty %}branch, specifically used to handle the case where the list is empty.

For example, when displaying an article list:

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <li>
        <a href="{{ item.Link }}">
            <h5>{{ item.Title|default:'暂无标题' }}</h5>
            <div>{{ item.Description|default:'暂无简介' }}</div>
        </a>
    </li>
    {% empty %}
    <li>
        <p>当前分类下暂无文章,敬请期待!</p>
    </li>
    {% endfor %}
{% endarchiveList %}

This method is better than adding an extra oneforoutside the loopifJudgment is more concise and readable, it combines the logic of 'traversal' and 'empty state handling' closely together.

Practical application scenario

Apply these strategies to the daily display of website content, which can greatly enhance the robustness and user experience of the template:

  1. Website title, keywords, and description (TDK):UsetdkWhen fetching the TDK information of the page, it can be combineddefaultThe filter ensures that even if the backend is not filled in, the front-end also displays a reasonable default value.<title>{% tdk with name="Title" siteName=true %}|{% system with name="SiteName"|default:"我的网站" %}</title> <meta name="description" content="{% tdk with name="Description" %}|{% system with name="SiteName"|default:"这是一个提供优质内容的网站" %}">

  2. Images and links in the content details:On the article or product detail page, if the Logo or specific image field may be empty, you can use conditional judgment to display the default image or hide the image placeholder.{% archiveDetail logo with name="Logo" %} {% if logo %}<img src="{{ logo }}" alt="{% archiveDetail with name='Title' %}" />{% else %}<img src="/static/images/default-product.jpg" alt="默认产品图片" />{% endif %}

  3. Display of custom field:When custom fields are defined in the content model but not all content may be filled in, usedefaultThe filter can prevent blank output.{% archiveParams params with sorted=false %} {% if params.author %}<p>作者: {{ params.author.Value|default:"匿名作者" }}</p>{% endif %}Or directly in the loop:<span>{{ item.Name }}:{{ item.Value|default:"未填写" }}</span>

  4. Contact information or friend link:Even if no contact information or friend link is set, you can still access it:ifDetermine to control the display of the entire block, avoiding unnecessary empty areas.{% contact cellphone with name="Cellphone" %} {% if cellphone %}<div>联系电话:{{ cellphone }}</div>{% endif %}

By proficiently using these template techniques, you will be able to build a more stable, professional, and user-friendly Anqi CMS website.


Frequently Asked Questions (FAQ)

Q1:defaultanddefault_if_noneWhat are the main differences between the filter in AnQi CMS template?A1: The main difference lies in their definition of 'empty'.defaultThe filter handles various 'empty' values, including empty strings.""numbers0and a boolean valuefalseand empty lists, etc.default_if_noneThe filter is stricter, it only takes effect when the value of the variable isnil(i.e., in Go language)null). This means that if you want to set a default value for a variable that really has no value, default_if_noneMore precise; if a variable may appear to be empty for various reasons (such as an empty string or zero),defaultit is more general.

Q2: How can I set a default placeholder image for images that may not exist in the template?A2: You can useifstatements to combinedefaultOr specify the default image path directly. For example, for article thumbnailsitem.Thumb:

{% if item.Thumb %}
  <img src="{{ item.Thumb }}" alt="{{ item.Title|default:'文章图片' }}">
{% else %}
  <img src="/static/images/placeholder.jpg" alt="默认占位图">
{% endif %}

to/static/images/placeholder.jpgReplace with the actual default image path.

Q3: When myarchiveListorcategoryListThere is no tag query result, how can you politely prompt the user with 'No content'?A3: You canforUse loop tags inside{% empty %}Tags to handle this situation. Whenforthe list being traversed by a loop is empty,{% empty %}The content inside the block will be rendered.

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {% for item in archives %}
        {# 正常显示文章内容的 HTML 代码 #}
        <p>{{ item.Title }}</p>
    {% empty %}
        {# 列表为空时显示的内容 #}
        <p>抱歉,此分类下暂无文章发布。</p>
    {% endfor %}
{% endarchiveList %}

This method provides a concise, efficient, and easy-to-maintain solution for handling empty content.

Related articles

How to perform addition or other arithmetic operations on numbers or strings in the template?

In website template development, we often need to perform some basic arithmetic operations, such as calculating the sum, adjusting values, or comparing values based on specific conditions.AnQiCMS (AnQiCMS) boasts an efficient architecture based on the Go language and a flexible template engine inspired by the Django style, providing users with an intuitive and powerful way to perform arithmetic operations such as addition of numbers or strings in templates.

2025-11-08

How to use a filter to truncate the specified character length of an article description or abstract and automatically add an ellipsis?

In website operation, the presentation of article description or abstract is crucial for user experience and Search Engine Optimization (SEO).A well-balanced, concise summary that not only attracts visitors to click but also helps search engines better understand the page content.However, manually controlling the length of each article summary is time-consuming and prone to errors.Fortunately, AnqiCMS provides powerful template filter functions that can help us automate this process, ensuring the uniformity and beauty of website content display.Why is it necessary to truncate article descriptions or summaries

2025-11-08

Besides `stampToDate`, which filters can format time values into a specified date format?

In AnQi CMS template development, we often need to display the time values stored in the database, such as the publication time and update time of articles, in the date and time format we expect.The `stampToDate` filter is undoubtedly one of the most commonly used and powerful tools, which can flexibly convert Unix timestamps to various date formats.

2025-11-08

How to combine custom parameters (such as "area", "house type") for multi-condition filtering on the article list page?

In AnQi CMS, to implement multi-condition filtering on the article list page, such as filtering based on custom parameters such as "area" and "house type", it requires us to cleverly combine the system-provided "content model" feature with the "document parameter filtering tag" ("archiveFilters") and "document list tag" ("archiveList") of the front-end template.The entire process can be divided into several core steps, let's take a detailed look together.### Core Function: Customize Content Model and Parameters Basic Implementation of Multi-Condition Filtering

2025-11-08

How to use a filter to remove specific characters (such as spaces) from the beginning, end, or any position of a string?

String cleaning practical guide in AnQiCMS: Efficiently remove filters for specific characters During the operation of a website, we often encounter situations where we need to clean and format string data.Whether it's the extra spaces typed by users or redundant characters carried in when importing content from external sources, these subtle details may affect the neatness of website content and the user experience.AnQiCMS (AnQiCMS) provides a multifunctional and easy-to-use template filter that can help us easily deal with these string cleaning needs.

2025-11-08

How to use a filter to automatically find URLs in text and convert them into clickable HTML links?

In website operation, we often encounter such needs: in the content or description of the article, some URLs or email addresses may be included, but they are just plain text, and users cannot click to access directly.Manually adding HTML links to each URL is inefficient and prone to errors, especially when the volume of content is large.AnQiCMS (AnQiCMS) understands this pain point and provides powerful built-in filters to help us easily automate the conversion of URLs in text, making website content more friendly and convenient.### Automated Link

2025-11-08

How to ensure that HTML code is correctly parsed and not escaped when displaying rich text content using the `safe` filter?

In AnQi CMS, rich text content usually carries articles, product descriptions, or page details with rich information. This content often includes various HTML tags such as bold, italic, images, links, tables, and so on.If this HTML code is not parsed correctly and is simply displayed as plain text, then what the user sees on the front end is a pile of code, rather than beautiful and structured content. This clearly has a negative impact on the readability and professionalism of the website.

2025-11-08

If the article content is in Markdown format, how to use the `render` filter to render it as HTML?

AnQi CMS is favored by many users for its efficient and flexible content management capabilities.In content creation, Markdown format has become the preferred choice for many content creators due to its simplicity and efficiency.But how to beautifully present these Markdown-formatted contents as structured HTML on the website front-end is a concern for many users.

2025-11-08