How to ensure that the AnQiCMS template does not cause page rendering errors when the variable is `nil`?

Calendar 👁️ 69

When using AnQiCMS to build a website, we often encounter the situation where template variables may be empty (nilThe case where. For example, a document may not have a thumbnail set, or a custom field may not be filled in.If the template code does not properly handle these potential null values, errors may occur during page rendering, affecting user experience and even causing some website functions to be unavailable.Fortunately, AnQiCMS's template engine provides various mechanisms to help us elegantly handle these variables asnilto ensure the stability and smoothness of the page.}

AnQiCMS's template syntax is similar to the Django template engine, it uses double curly braces{{变量}}to output variable content, as well as single curly braces and percent signs{% 标签 %}To control the logical flow. Understanding these basic grammars and how to use them in conjunction with filters (filters) and tags (tags) is to avoidnilThe key that causes rendering errors due to variables.

1. Useiftag for conditional judgment

The most direct and effective method is to useifTags make conditional judgments on variables. In AnQiCMS templates,{% if 变量 %}Syntax determines if a variable is “defined”. Typically, this means the variable is notniland not an empty string""nor a number0or a boolean valuefalse.

For example, we want to display the description of the article, but some articles may not have filled in the description. If output directly{{ archive.Description }}When the description is empty, the page may display a blank screen or cause errors in some strict environments. We can handle it like this:

{% if archive.Description %}
    <p>{{ archive.Description }}</p>
{% else %}
    <p>暂无文章简介。</p>
{% endif %}

If we need to ensure that a certain image field (such asarchive.Logoorarchive.ThumbRender only if it exists<img>Then tagifIt is very practical to judge

{% if archive.Logo %}
    <img src="{{ archive.Logo }}" alt="{{ archive.Title }}" />
{% else %}
    <!-- 方案一:显示一个默认占位图 -->
    <img src="/static/images/default-logo.png" alt="默认图片" />
    <!-- 方案二:或者干脆不显示图片 -->
{% endif %}

For boolean variables such asitem.HasChildren)ifThe tag can also well judge its true or false, thereby deciding whether to render the child element:

{% if item.HasChildren %}
    <ul>
        <!-- 渲染子分类列表 -->
    </ul>
{% endif %}

By{% if not 变量 %}Sentences, we can also conveniently check whether the variable isnilor null, and provide alternative content, for example when handling 'Previous/Next' document navigation:

{% prevArchive prev %}
上一篇:
{% if not prev %}
  <span>没有了</span>
{% else %}
  <a href="{{ prev.Link }}">{{ prev.Title }}</a>
{% endif %}
{% endprevArchive %}

Second, usingdefaultanddefault_if_noneThe filter provides a default value

AnQiCMS template engine providesdefaultanddefault_if_noneA filter that provides a preset default value when a variable is empty. This is very convenient for handling empty values of variables inline.

defaultThe filter will replace the variable withnilan empty string""numbers0or a boolean valuefalseProvide a default value. For example, ifarchive.Titleis empty, we can make it display "No Title Article":

<h1>{{ archive.Title|default:"无标题文章" }}</h1>

For imagessrcProperty,defaultThe filter can also be used, to ensure that even if the image path is empty,srcProperties can also have a valid default value to prevent the browser from displaying broken image icons:

<img src="{{ archive.Thumb|default:"/static/images/placeholder.jpg" }}" alt="{{ archive.Title|default:"文章图片" }}" />

Anddefault_if_noneThe filter is more precise, it will only trigger when the variable is strictly equal to:nil(i.e., in Go language)nilProvide a default value when a variable is empty. This is very useful in scenarios where it is necessary to distinguish between 'not set' and 'set to zero/empty'.""numbers0or a boolean valuefalsebut notnil, thendefault_if_noneWill not interfere. This is very useful in scenarios where it is necessary to distinguish between 'not set' and 'set to zero/empty'.

For example, a numeric fieldarchive.PriceMay be set as0(indicating free), may also benil(indicating unknown price). If0is a valid value, whilenilthen it is necessary to default,default_if_noneMore suitable:

价格:{{ archive.Price|default_if_none:"价格待定" }} 元

Third, in the loopemptyStatement handles empty list

When we need to traverse a list (array or slice), if the list is empty, we can directly use{% for %}A loop may cause nothing to be displayed on the page, confusing the user. AnQiCMS providesforloop tags to{% empty %}solve this problem.

In{% for %}use labels inside{% empty %}When the traversed list is empty,{% empty %}and{% endfor %}the content between them will be rendered to provide a friendly prompt.

For example, when displaying an article list:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <li>目前还没有任何文章。</li>
    {% endfor %}
{% endarchiveList %}

So, even ifarchivesThe list is empty, the page will not appear blank, but will display a prompt saying “There are no articles at the moment.”.

4. Combination usage: Build a more robust template.

In practical development, we often need to combine the above strategies to build more robust and less error-prone templates.

For example, a content block may include a title, description, and image. We want to display the entire content block if a title or description exists, and the image has a default value:

`twig {% if archive.Title or archive.Description %}

<div class="article-summary">
    <h2>{{ archive.Title|default:"最新动态"

Related articles

In AnQiCMS template, which filters or tags behave in three states of 'or and not' logic for `nil` values?

In AnQiCMS template development, efficiently and robustly handling data is the key to building dynamic websites.Especially when the data obtained from the backend may contain `nil` (empty) values, it is particularly important to elegantly display content, provide default values, or execute specific logic in the template.AnQiCMS provides various filters and tags that can help us display three states of existence, non-existence, or undefined for `nil` values, thereby enhancing the flexibility and user experience of templates.### One, directly judge whether the data exists: `if`

2025-11-09

What does the `stringformat` filter return when it fails to handle formatting in the AnQiCMS template?

AnQiCMS (AnQiCMS) boasts its efficient architecture based on the Go language and flexible template engine, bringing great convenience to content management.In daily content operation, we often need to present data in a specific format on the website front-end, which cannot do without various practical template filters.The `stringformat` filter is a powerful tool for data formatting, allowing us to format numbers, strings, and even more complex data types in a precise way, similar to the `fmt.Sprintf` function in the Go language.Understand

2025-11-09

How to display the detailed structure, type, and value of the `dump` filter in AnQiCMS template debugging?

During the development and maintenance of AnQiCMS templates, we often encounter situations where we need to confirm the content of variables.Improper use of template tags or an unexpected data structure passed from the backend can lead to page display errors.If you can see the internal structure, type, and current value of a variable at this time, it will undoubtedly greatly improve our debugging efficiency.In the AnQiCMS template system, the `dump` filter was born to solve this pain point, it's like a periscope, helping us to understand the 'inner nature' of template variables.### The pain points of template debugging and

2025-11-09

What is the result of repeatedly outputting an empty string in the `repeat` filter of AnQiCMS templates?

AnQiCMS's template system is renowned for its concise and efficient Django-style syntax, which allows content developers to easily build dynamic pages.In daily template development, we often use various filters to process and format data.Among them, the `repeat` filter is a very practical tool that can repeat a string according to the specified number of times.However, when using the `repeat` filter, some developers may encounter a seemingly simple but easily confusing problem: when

2025-11-09

How to combine `if` and `yesno` filters in AnQiCMS templates to display different prompts based on VIP status and expiration time?

In website operations, providing differentiated services and content prompts to different user groups is a key link in improving user experience and achieving business goals.Especially on websites with a VIP membership system, displaying personalized information based on the user's VIP status and even the expiration time of the membership can greatly enhance the user's sense of belonging and willingness to interact.AnQiCMS (AnQiCMS) relies on its flexible template engine and rich tags, filters, making everything simple and efficient.Today, let's discuss how to use the AnQiCMS template

2025-11-09

How to determine if the boolean value of a custom field in the AnQiCMS template is true and dynamically add a CSS class?

In AnQiCMS template development, we often need to adjust the display style of the page based on the specific attributes of the content.This includes dynamically adding CSS classes based on the boolean value of custom fields (i.e., true or false status), thus achieving a more flexible and expressive interface.AnQiCMS with its flexible content model design allows users to create various custom fields for different content types (such as articles, products).These custom fields greatly enrich the expression of content, enabling templates to be highly customized for different business needs.###

2025-11-09

In AnQiCMS template, how to add a recommended icon to the article title based on the boolean state of the `item.Flag` attribute?

When managing website content in AnQiCMS, we often hope to highlight important articles through some intuitive visual elements, such as adding a prominent small icon to recommended content.This not only attracts the attention of visitors, but also helps them quickly find high-quality information on the website.It is fortunate that AnQiCMS has built-in `item.Flag` properties and a flexible template engine, making it very easy to implement this requirement.This article will discuss in detail how to use the `item.Flag` attribute status in the AnQiCMS template

2025-11-09

How to calculate the number of times a specific keyword appears in a string or array using the `count` filter in AnQiCMS templates?

During the template development process of AnQiCMS, we often need to perform dynamic data analysis or display of page content, such as counting the frequency of a keyword or checking the number of specific elements in a list.At this time, the `count` filter has become a very practical tool.It can help you quickly and efficiently calculate the number of times a specific keyword appears in a string or array, providing the possibility of flexible template presentation.--- ### `count` filter: Accurately count your content In short, `count`

2025-11-09