How to elegantly handle null or undefined variables returned by the database in AnQiCMS templates to avoid page errors?

Calendar 👁️ 71

During the development of website templates, we often encounter a headache: when the data obtained from the database is empty (null) or a variable is undefined in a particular situation, the template rendering will cause an error, resulting in the page not displaying normally and greatly reducing the user experience.AnQiCMS, based on its powerful Go language backend and flexible Django-style template engine, provides us with a variety of elegant solutions for handling such situations, allowing the template to run smoothly even when the data is incomplete.

Use conditional judgment well:{% if %}Tag

The most direct and most commonly used method is to check whether a variable exists or its value is valid through conditional judgment. In AnQiCMS templates, we can use the familiar{% if ... %}/{% elif ... %}and{% else ... %}Build flexible logic with structure.

When we need to check if a variable has a value, we can directly place it in.ifIn the statement. For example, if an article's summary (Description) may be empty, we can handle it like this:

{% if archive.Description %}
    <p>{{ archive.Description }}</p>
{% else %}
    <p>抱歉,暂无摘要信息。</p>
{% endif %}

For the list data returned from the database, we often need to judge whether the list is empty. AnQiCMS provides{% for %}a loop that{% empty %}tag, making it extremely concise to handle an empty 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 %}

WhenarchivesWhen the list is empty, the template will not display an empty<ul>label, but will output directly<li>暂时没有相关文章。</li>to avoid the feeling of emptiness on the page.

II. Provide alternative solutions for variables:defaultanddefault_if_noneFilter

In some cases, we do not want to output empty values or blanks, but provide a default alternative text, for which you can use the built-in AnQiCMS.defaultanddefault_if_noneFilters. They can provide a default value for variables that may be empty or undefined, avoiding direct output of empty content or triggering errors.

  • defaultFilterWhen a variable evaluates to a 'false' value (such as an empty string""numbers0and a boolean valuefalseor,nil)defaultThe filter will provide a specified value.

    <h1>{{ archive.Title|default:"无标题文章" }}</h1>
    <p>作者:{{ authorName|default:"匿名用户" }}</p>
    

    Ifarchive.TitleIt is an empty string, orauthorNameUndefined, they will respectively display 'No title article' and 'Anonymous user'.

  • default_if_noneFilterThis filter is more focused on processing the Go language in.nil(equivalent to null in other languages) value. It will only apply the default value when the variable is exactlynil. If the variable is an empty string or 0, it will not take effect.

    <p>联系电话:{{ contact.Cellphone|default_if_none:"暂无联系方式" }}</p>
    

    Ifcontact.CellphoneThis variable's value isnilIf there is no contact information displayed.contact.CellphoneIs an empty string""It will directly display an empty string. Choose which filter to use depending on the specific 'empty' state you expect to handle.

Three, ensure content safety and format:safeFilter

Although it does not directly handle null values, when the content returned by the database may contain HTML tags (such as content stored in rich text editors),safeThe filter is crucial for avoiding page errors and ensuring correct content rendering.The AnQiCMS template, for security reasons, defaults to escaping all output to prevent cross-site scripting (XSS) attacks.If you need to output HTML content without being escaped, you must usesafeFilter:

<div>
    {# archive.Content通常包含HTML内容,需要safe过滤器 #}
    {{ archive.Content|safe }}
</div>

If not added|safeHTML tags will be output as is, rather than parsed by the browser, which may affect page layout and content display.

4. Declare variables in advance:{% set %}and{% with %}Tag

When dealing with complex logic or in specific areas of the template where temporary storage of calculation results is needed, it is a good habit to declare variables in advance.This can avoid problems caused by undefined variables in subsequent code.

  • {% set %}Tag: Used to define a new variable within the current template scope.

    {% set articleCount = archives|length %}
    <p>本分类共有 {{ articleCount }} 篇文章。</p>
    
  • {% with %}Tag: Mainly used for.{% include %}The template fragment passes local variables, or defines temporary variables within a specific logic block. The variables defined are only available within{% with %}to{% endwith %}.

    {% with featuredArticle=archives|first %}
        {% if featuredArticle %}
            <h2>今日推荐:{{ featuredArticle.Title }}</h2>
        {% endif %}
    {% endwith %}
    

    here,featuredArticlevariables are onlywiththe block, avoiding pollution of global variables or unexpected side effects.

By flexibly applying these techniques, you can handle various situations of null or undefined variables returned by the database in AnQiCMS templates, making your website not only powerful but also excellent in stability and user experience.


Frequently Asked Questions (FAQ)

  1. defaultanddefault_if_noneWhat are the differences between filters, and when should I use them? defaultFilters provide a default value when the variable is "false" (includingnilan empty string""numbers0and a boolean valuefalse). While thedefault_if_nonefilter is more strict, it only applies when the variable is exactly equal tonilOnly when a default value is provided, if the variable is an empty string or other 'false' value, it will not take effect.

    • If you want to provide a universal default value for all types of 'empty' values (including undefined, empty strings, zero, etc.), usedefault.
    • If you need to distinguishnilAnd other "empty" values (for example, a field explicitly not set is different from a field set to an empty value), or a variable may be a pointer but not initialized, thendefault_if_noneIs a more precise choice.
  2. Why is it still possible to see the word 'nil' on the page even though these methods were used?This usually happens in the following situations:

    • You have useddefaulta filter, but the value of the variable is notnilIt is a pointer, notnilof type (for example,*stringa variable of type, with the valuenil), or an empty structure, etc. At thisdefaultit may not be considered a 'false' value.
    • You are trying to directly output anilvariable for the value, but forget to usedefault_if_noneorifa statement for judgment. In Go language,nilThe value is usually displayed as "nil" when output directly in the template.
    • The variable is not truly undefined or empty, but rather one of its nested fields is empty ornil. But you accessed the outer variable directly. At this point, you need to further check and judge the nested fields.
  3. In the loop, besidesemptyTags, how can I handle more complex null value situations? {% for ... empty %}The structure is very suitable for providing default content when the list is empty. If your 'empty value situation' involves each element in the loop body having a specific field that may be empty, or if you need to control the data in the loop more finely, you can combine the use ofifanddefaultFilter. For example, you can use it in each loop.itemAgain inside.{% if item.field %}or{{ item.field|default:"默认值" }}Come handle the empty value of a single element. In addition, if the elements in the list are complex types, consider preprocessing the data at the Go backend code level before passing it to the template to ensure the integrity and consistency of the data.

Related articles

What is the difference between the `default_if_none` filter and the `default` filter in the AnQiCMS template, and when should the former be preferred?

In web template development, handling the case where variables may not exist or are empty is a common task.The AnQiCMS template system provides a variety of filters to help us elegantly handle such issues, with `default` and `default_if_none` being two commonly used tools.They both provide a default value when the variable is 'no value', but there is a subtle but important difference in the definition of 'no value'.Understanding these differences can help us control the display of template content more accurately.###

2025-11-09

How to set default display content for possibly empty variables in the `default` filter of AnQiCMS templates?

In Anqi CMS template design, we often encounter situations where variable values may be empty.For example, an article may not have a thumbnail set or a product field may be temporarily unfilled.If the template directly displays these empty values, ugly blank spaces will appear on the page, affecting user experience, and may even confuse visitors.To solve this problem, Anqi CMS provides a very practical filter mechanism, where the `default` filter is the key tool to ensure the continuity of content display.### `default` Filter

2025-11-09

How to avoid excessive nesting of `if` statements in AnQiCMS templates to improve code readability?

In AnQiCMS template development, we often encounter situations where we need to display different content based on different conditions.Newcomers may tend to use the `{% if condition %}` statement extensively. As the project requirements grow, these conditional judgments become nested layer by layer, which quickly makes the template difficult to read, maintain, and even hides potential logical errors.Code readability once reduced, not only will the development efficiency be affected, but the future feature iteration and problem troubleshooting will also become extremely difficult.Fortunate is that AnQiCMS is based on Go language Django-like

2025-11-09

The `in` operator in the AnQiCMS template's `if` statement, how to judge whether an element exists in an array or set?

When developing the AnQiCMS website template, we often need to dynamically display or hide content based on certain conditions.A common requirement is to determine whether an element exists within a dataset, such as checking if a user has a specific role or if the current article has a specific tag.AnQiCMS's template engine provides a concise and powerful `in` operator that can easily solve such problems. ### Core Function Explanation: What is the `in` operator?The design inspiration of AnQiCMS template engine comes from Django

2025-11-09

In AnQiCMS template, how to decide whether to display the default image or placeholder based on the existence of a variable?

In the template development of AnQiCMS, we often encounter situations where the content may not contain images.For example, a news article may not have an illustration, or a certain product in a product list may not have uploaded the main image temporarily.In this case, if the template directly calls the image address, it may display a broken image icon or leave an abrupt blank, which undoubtedly affects the overall aesthetics and user experience of the website.To solve this problem, AnQiCMS provides flexible template tags and filters, allowing us to determine whether the image variable exists

2025-11-09

In AnQiCMS template, how to judge if the list is empty and display a prompt of 'No content'?

When using AnQiCMS for website template development, you often encounter situations where you need to display list data, such as article lists, product lists, or image galleries.When we retrieve data through template tags (such as `archiveList` or `categoryList`) and use a `for` loop to iterate over the list, if the list is empty, it is usually necessary to provide the user with a friendly prompt instead of displaying a blank space.How can you elegantly judge whether a list is empty in a `for` loop and display a 'No content' prompt?

2025-11-09

How to judge if there is a thumbnail in the `archiveList` tag in AnQiCMS template through `if` to selectively display images?

In AnQiCMS template development, displaying list content is a common requirement, and how to elegantly handle the images in these lists, especially thumbnails, is directly related to the visual effects and user experience of the website.The `archiveList` tag is one of the core content call tags of AnQiCMS, which helps us flexibly obtain various document lists.However, in practice, we often encounter situations where certain documents have not set thumbnails, which may lead to broken images or layout confusion on the page. At this time

2025-11-09

How to display different content in the AnQiCMS template based on the value of the `item.Status` field (such as approved, in review)?

In website content operation, the review status of the content is a very important link.Whether it is a comment submitted by the user, a forum post, or an article or product information released by the website administrator, it often needs to be reviewed before it can be displayed to the public.AnQiCMS provides a flexible template mechanism that allows us to easily display different content on the front-end page based on the review status of the content (such as "approved" or "in review"), thereby providing users with clearer and more accurate feedback.AnQiCMS template syntax is similar to the Django template engine

2025-11-09