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

Calendar 👁️ 70

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 existnilWhen a value is empty, how a template elegantly displays content, provides default values, or executes specific logic becomes particularly important. AnQiCMS provides various filters and tags to help us targetnilThe value shows three states of logic such as 'exists', 'does not exist', or 'undefined', thereby enhancing the flexibility of the template and the user experience.

1. Directly determine whether the data exists:ifLogical judgment tag andfor...emptyLoop structure

The most basic and most commonly used method is to use conditional judgment tagsifTo check if data or variables exist. AnQiCMS's template engine willnilValues, empty strings, zero, or empty collections (such as empty arrays or empty slices) are considered boolean contexts infalse. This means that when a variable or object isnilthen,{% if 变量名 %}it will executeelseBranch indicating a state of "non-existent" or "no content."

For example, when we try to display the details of a document, but the document may not exist:

{% archiveDetail myArchive %} {# 尝试获取当前文档详情,如果不存在,myArchive将为nil #}
{% if myArchive %}
    <h1>{{ myArchive.Title }}</h1>
    <p>{{ myArchive.Description }}</p>
{% else %}
    <p>抱歉,您查找的文档不存在。</p>
{% endif %}

This pattern clearly demonstrates the binary logic of 'existence' and 'non-existence'.

Similarly, for labels that may return an empty collection (such as document lists, friend link lists), AnQiCMS providesfor...emptyA loop structure that is specifically used to handle the third state of 'the list is empty':

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
        <li><a href="{{item.Link}}">{{item.Title}}</a></li>
    {% empty %}
        <li>当前没有任何内容可以显示。</li>
    {% endfor %}
{% endarchiveList %}

Here, ifarchivesIf the list contains data, then executeforLoop body; ifarchivesIt is empty, then executeemptyBlocks. This directly provides two clear visual feedbacks, 'has content' and 'no content', which is very suitable for handling list data that may be empty.{% linkList %}/{% tagList %}with tags配合iforfor...emptyis also often used in such scenarios.

Chapter 2: A precise filter for handling null values:defaultwithdefault_if_none

In addition to condition judgment, AnQiCMS also provides filters tonilset default alternative content for null values.

defaultFilters can be used for variables (includingnilAn empty string, zero value, etc. Provides a fallback value when empty. It provides an 'or' alternative for any 'empty' state:

{{ document.Title|default:"无标题" }}

Ifdocument.TitleIs an empty string ornilIt will display "untitled".

Anddefault_if_noneThe filter is more precise, it is specifically fornil(Typically refers to a pointer type or an uninitialized variable) provides a default value. If the variable value is an empty string or zero, but notnilIt will not apply the default value. This helps distinguish between the two cases of 'having a value but it is empty' and 'there is no value at all', showing a more detailed 'or' state processing:

{# 假设后端user对象可能为nil,或者其UserName字段可能为空字符串 #}
{{ user.UserName|default_if_none:"访客" }} {# 如果user或UserName为nil,显示“访客” #}
{{ user.UserName|default:"匿名用户" }}   {# 如果user或UserName为nil或空字符串,显示“匿名用户” #}

Bydefault_if_noneYou can provide an explicit default representation for those truly 'unset' data, distinguishing them from those 'set but empty'.

Three, clear three-state logic:yesnoFilter

yesnoThe filter is a powerful tool directly implemented in AnQiCMS templates to handle the three state logic of "OR" and "NOT", especially for processing boolean values or nullable data. Its default behavior is:

  • If the value istrueoutput 'yes'.
  • If the value isfalseoutput 'no'.
  • If the value isnil(or considered asnil), output 'maybe'.

This three-state logic is very useful when it is necessary to clearly distinguish between "yes", "no", and "unknown/unset" scenarios. For example, a user's VIP status may be enabled, disabled, or never set:

{{ user.IsVip|yesno }} {# 可能会输出 yes, no, 或 maybe #}

More flexible is,yesnoThe filter allows us to customize the output text of these three states, making its presentation fully fit the actual business requirements:

{{ user.IsVip|yesno:"已启用,已禁用,未设置" }}

Now, ifuser.IsVipWithtrueDisplaying "Enabled"; forfalseDisabled is displayed; fornilThis displays "Not set". It perfectly demonstrates the three states of "OR AND NOT": namely, "Condition is true", "Condition is false", and "Condition is not evaluated (due to missing data)".

Summary

In AnQiCMS template design, understanding and applying these fornilvalue handling mechanisms can greatly enhance the robustness and user experience of the template. Whether throughifandfor...emptyImplement binary judgment and list empty status handling, throughdefaultanddefault_if_noneProvide detailed default values, or useyesnoThe filter implements a clear three-state logic, these tools can all help us build more flexible, reliable, and user-friendly content display pages.


Frequently Asked Questions (FAQ)

1. Why does AnQiCMS provide multiple ways to check the 'empty' state of data? What are the differences?

AnQiCMS provides various methods to adapt to different concepts of 'empty.'ifTags andfor...emptyBlocks are mainly used for logical judgments and loop control, they willnilAnd empty strings, zero values, and empty sets are considered boolean.false.defaultThe filter is the same, providing default values for all of these 'empty' states and so on.default_if_noneandyesnoThe "maybe" state is more precise, mainly distinguishingnil(which means the variable has not been assigned any value or points to an empty) and other "empty values" (such as empty strings)""or numbers0The difference. Understanding these differences can help you choose the most suitable tool, and write more accurate template logic.

2. UseyesnoCan you customize the output other than 'yes', 'no', 'maybe' when using the filter?

Of course you can.yesnoThe filter allows you to provide a comma-separated string to fully customize the display text for these three states. For example,{{ variable|yesno:"真棒,遗憾,待定" }}will be displayed separatelyvariableWithtrue/falseandnilWhen, output "Great", "Regret" and "Undecided". This flexibility makesyesnovery useful when specific business terminology is needed.

3. If a variable may benilAnd will there be a template rendering error if I try to access its properties directly?

Yes, if a variable isnilAnd if you directly try to access its properties (such as{{ myVar.Property }}), AnQiCMS' template engine usually throws an error, causing the page to render中断 or display abnormalities. In order to

Related articles

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 does the `split` filter handle empty strings or strings without the specified delimiter in AnQiCMS templates?

In AnQiCMS template development, string processing is a common requirement.Sometimes we need to split a string containing multiple values into individual items so that they can be traversed on the page for display or further processing.At this time, the `split` filter has become a powerful assistant for template developers.It can split a string into an array (or slice) based on a specified delimiter, greatly simplifying the logic of complex data display.However, some specific scenarios when using the `split` filter may confuse developers who are new to the field

2025-11-09

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

When building a website with AnQiCMS, we often encounter the situation where template variables may be empty (`nil`).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, the AnQiCMS template engine provides various mechanisms to help us elegantly handle the cases where variables are `nil`, ensuring the stability and smoothness of the page

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