How to set a default display value for possibly empty variables in AnQiCMS templates?

Calendar 👁️ 66

When using AnQiCMS to build a website, we often encounter such situations: some content fields may not have values every time, such as articles may not have thumbnails, products may not have detailed descriptions, or some contact information may not have been filled in.If variables that may be empty are directly called in the template, ugly blank spaces may appear on the page, or even program errors, which will greatly affect the user experience and the professionalism of the website.

Fortunately, AnQiCMS's template system is based on syntax similar to Django and Blade, providing a powerful and flexible mechanism to handle these situations, allowing us to set elegant default display values for variables that may be empty.

1. UsedefaultFilter settings basic default value

The most direct and commonly used method is to use the built-in AnQiCMS template.defaultThe filter. Its function is very simple: it automatically displays the default value you set when the variable does not exist or its value is empty. Here, "empty" usually includes empty strings, boolean valuesfalsenumbers0and in Go languagenil.

is very intuitive, just pass through the pipe symbol after the variable name|连接defaultfilter, and specify your default text with double quotes.

For example, if your article summaryarchive.DescriptionMay be empty, and you want to display "No introduction" in this case, you can write it like this:

<p>{{ archive.Description|default:"暂无简介" }}</p>

Similarly, for some contact methods that may not exist, such as WhatsApp, if the background is not filled in, we can give it a default prompt:

<p>WhatsApp: {{ contact.WhatsApp|default:"未设置" }}</p>

So, even ifarchive.Descriptionorcontact.WhatsAppIn the database, it is empty, and there will be no blank on the page, but it will display "No introduction" or "Not set" in a friendly manner, ensuring the integrity of the content.

2. Precisely handle empty values:default_if_noneFilter

Under certain specific scenarios, you may need to make a more accurate judgment, only for variable values ofnil(indicating that the variable does not exist or is not assigned, rather than just an empty string) the default value is set, while an empty string is retained as is. AnQiCMS provides for thisdefault_if_nonefilter.

This filter is compatible withdefaultThe main difference is that it only targetsnilvalue takes effect. If the variable's value is an empty string ("")default_if_noneit will treat it as a valid value and display it, whereasdefaultit will be considered as "empty" and display the default value.

The way to use withdefaultis the same as the filter:

<p>文章作者: {{ archive.Author|default_if_none:"匿名读者" }}</p>

Assumearchive.AuthorField:

  • If it isnil: Display "Anonymous Reader".
  • If it is""(Empty string): Display an empty string (i.e., no content is displayed).
  • If it is"张三": Display "Zhang San".

Understand the subtle differences between these two filters, which can help you control the rendering logic of the template more accurately.

3. Use conditional judgment{% if %}Tag rendering of different structures

In addition to setting default text directly, sometimes you may need to display a completely different content structure based on the existence of variables, or even not display certain blocks. AnQiCMS templates support syntax similar to Django's{% if 条件 %}Label, which allows us to flexibly perform conditional rendering.

When a variable has a value, display a segment of HTML; when the variable is empty, display a different HTML structure, or a placeholder image.This is particularly useful when handling images, ad slots, and optional content modules.

For example, to set a default thumbnail for an article: We first obtain the article's logo image througharchiveDetailLabel to get the article's logo image, and then use{% if %}to judge.

{% archiveDetail articleLogo with name="Logo" %}
{% if articleLogo %}
    <img src="{{ articleLogo }}" alt="文章图片">
{% else %}
    <img src="/public/static/images/default-thumbnail.jpg" alt="默认缩略图">
{% endif %}

The logic of this code is: ifarticleLogoThe variable has a value (i.e., the article has an accompanying image), then display this image.Otherwise, display a preset default thumbnail. This can prevent layout errors on the page or damage to the placeholder due to missing images.

For example, some contact information is displayed with a link only when it has a value:

{% contact email with name="Email" %}
{% if email %}
    <p>联系邮箱:<a href="mailto:{{ email }}">{{ email }}</a></p>
{% endif %}

IfemailIf the variable is empty, the wholepTags will not be rendered, keeping the page simple.

4. Advanced Techniques: Predefined Variables and Flexible Reuse({% set %}or{% with %})

In some cases, you may want to set an initial default value for a variable at the top of a template file or within some logical block, and then refer to this variable in multiple places. AnQiCMS provides{% set %}and{% with %}To achieve this with a tag.

  • {% set %}Define a local variable: {% set %}The tag is used to define a new variable in the current template file, which can be used anywhere after its definition.

    {% set articleTitle = archive.Title|default:"无标题文章" %}
    <h1>{{ articleTitle }}</h1>
    <p>页面标题:{{ articleTitle }}</p>
    

    here,articleTitleThe variable has been assigned.archive.TitleThe value, ifarchive.Titleis empty, then use 'No Title Article' as the default value. After that, we can reuse it multiple timesarticleTitle.

  • {% with %}Define scope variables: {% with %}Tags are used to define one or more variables within a specified block, which are only valid in{% with %}and{% endwith %}between. It can also be used to pass default values in{% include %}tags. It is also valid within a

    {% with defaultDesc="此内容暂无详细描述。请等待后续更新。" %}
        <p>{{ archive.Description|default:defaultDesc }}</p>
    {% endwith %}
    

    In this example,defaultDesconly{% with %}block, used to providearchive.DescriptionSet default value.

Summary

In AnQiCMS template, setting a default display value for variables that may be empty is a key step in building a robust and user-friendly website.

  • For simple text content missing, use directlydefaultFilteris the most convenient way.
  • Need to distinguish strictlynilAnd for empty strings,default_if_noneFilterProvided more refined control.
  • When it is necessary to display different HTML structures based on the existence of variables,{% if %}Conditional judgmentit is indispensable.
  • And{% set %}or{% with %}TagIt can help you manage and reuse default variables more effectively, making template code clearer.

Master these skills, and you will be able to create more stable and elegant AnQiCMS website templates

Related articles

Which date and time formatting parameters are supported by the `date` filter in AnQiCMS?

In website content management, the accurate display of dates and times is crucial for improving user experience and ensuring the timeliness of information.AnQiCMS provides a flexible and powerful template engine, allowing you to easily customize the display of dates and times on web pages.Among many practical tools, the `date` filter is an important member for handling date and time formatting.### `date` filter: A powerful tool for formatting date and time The `date` filter in AnQiCMS templates is used to format `time.Time`

2025-11-08

How to format a `time.Time` object into a specified date string in AnQiCMS template?

In website content operation, the way dates and times are presented often directly affects user experience and the clarity of information.A professional, readable date format can not only enhance the credibility of the content, but also allow visitors to obtain key information faster.AnQiCMS as a powerful content management system naturally also provides a flexible way to handle and format date and time.When we need to display the publication time, update time, or any other date information in the AnQiCMS template, we may encounter a problem

2025-11-08

How to remove specific characters from a string in the AnQiCMS template, such as spaces or special symbols?

In website content operation, we often encounter scenarios where we need to process string data.For example, the title, description, or keywords extracted from the database may contain extra spaces, unnecessary special characters, or even inconsistent prefixes or suffixes.These characters may not only affect the aesthetic beauty of the layout, but may also cause interference when performing data analysis or search engine optimization (SEO).AnQiCMS as an efficient content management system, deeply understands the needs of users in content processing.

2025-11-08

In AnQiCMS template, can the `count` filter count the number of occurrences of elements in an array?

In AnQiCMS template development, we often need to handle various data, one common requirement is to count the number of times a specific element or keyword appears.When faced with array or string data, the `count` filter can become your powerful assistant.So, can the `count` filter in the AnQiCMS template count the number of occurrences of elements in an array?The answer is affirmative, it can not only count the word frequency in a string, but also accurately count the number of occurrences of elements in an array.

2025-11-08

What is the difference between the `default` and `default_if_none` filters for handling null values in AnQiCMS?

In AnQiCMS template development, we often need to handle the case where data may be empty to ensure the stability of page display and user experience.AnQiCMS provides rich template filters to meet such needs, where `default` and `default_if_none` are very practical tools for handling null values.They are both intended to provide a fallback value for missing or empty data, but there is a subtle yet critical difference in the definition of 'empty,' understanding these differences can help us more precisely control the template rendering logic.###

2025-11-08

How to check if a number is divisible by another number in AnQiCMS template?

During the development of AnQiCMS templates, we often encounter situations where we need to adjust the display of content or apply different styles based on specific conditions.For example, when a number in the list meets a certain rule, such as being divisible by 3, we would like it to have a special performance.Lucky enough, AnQiCMS's powerful template engine provides a simple and efficient way to meet this requirement.This article will deeply explore how to flexibly judge whether a number can be evenly divided by another number in the AnQiCMS template, and provide practical code examples in real-world scenarios.### Core Function

2025-11-08

What type of value does the `divisibleby` filter in AnQiCMS return in mathematical operations?

In AnQiCMS template creation, we often need to control the display of content based on some mathematical logic, such as determining whether a number can be evenly divided by another number.At this point, the `divisibleby` filter is particularly important.It helps us easily implement this judgment in the template without writing complex logic code.The `divisibleby` filter returns a very intuitive and easy-to-understand boolean value when performing mathematical integer division.This means that the result can only be two possibilities: `True` (true) or

2025-11-08

How can you view the internal structure and value of a variable in AnQiCMS templates for debugging?

During the development and content operation of Anqi CMS templates, a deep understanding of the internal structure and specific values of variables in the templates is the key to efficient debugging.When you are faced with abnormal data displayed on a page or are unsure about the available properties of an object returned by a certain tag, being able to quickly view the detailed information of variables will undoubtedly greatly enhance the efficiency of solving problems. AnQi CMS provides a flexible and powerful template engine, which draws on the syntax of Django templates, and also includes some very practical debugging tools, allowing you to directly check variables in template files. Below

2025-11-08