During the development of website templates, we often encounter a headache-inducing problem: when the data obtained from the database is empty (null) or a variable is undefined under certain conditions, template rendering will cause errors, resulting in the page not displaying normally, which greatly reduces the user experience.AnQiCMS is based on its powerful Go language backend and flexible Django-style template engine, providing us with a variety of elegant solutions to handle such situations, allowing the template to run smoothly even when the data is incomplete.

1. Use conditional judgment:{% if %}Tag

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

We can directly put a variable into judgment when we need to check if it has a value.ifFor 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 list data returned from the database, we often need to determine whether the list is empty. AnQiCMS's{% for %}loop provides{% empty %}tags, making it exceptionally concise to handle empty lists.

{% 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 %}

whenarchivesThe template will not display an empty list when it is empty.<ul>Instead of labels, it outputs directly.<li>暂时没有相关文章。</li>This avoids the sense of emptiness on the page.

Secondly, provide backup solutions for variables:defaultanddefault_if_noneFilters

In some cases, we do not want to output empty values or whitespaces, but instead provide a default substitute text, at which time we can use the built-in AnQiCMSdefaultanddefault_if_noneFilters. They can provide a default value for variables that may be empty or undefined, to avoid directly outputting empty content or triggering errors.

  • defaultFiltersWhen a variable is evaluated to a 'false' value (e.g., an empty string""or a number0or a boolean valuefalse, ornil),defaultThe filter will provide a specified value.

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

    Ifarchive.Titleis an empty string, orauthorNameundefined, they will respectively display 'No title article' and 'Anonymous user'.

  • default_if_noneFiltersThis filter is more focused on handling Go language.nil(equivalent to null in other languages) value. Only when the variable is exactly equal tonilWhen it is applied, it will use the default value. If the variable is an empty string or 0, it will not take effect.

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

    Ifcontact.CellphoneThe value of this variable isnil, it will display "No contact information available".contact.Cellphoneis an empty string""If so, it will directly display an empty string. The choice of filter depends on the specific 'empty' state you expect to handle.

Ensure content safety and format:safeFilters

Although it does not directly handle null values, when the database returns content that may contain HTML tags (such as content stored in rich text editors),safeThe filter is crucial for avoiding page errors and ensuring content is correctly rendered.AnQiCMS template defaults to HTML escaping all output for security reasons to prevent cross-site scripting (XSS) attacks.safeFilter:

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

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

Four, declare variables in advance:{% set %}and{% with %}Tag

When it is necessary to temporarily store the result of computation in handling some complex logic or in specific areas of the template, declaring variables in advance is a good habit.This can avoid the problem caused by undefined variables in subsequent code.

  • {% set %}TagIt is used to define a new variable within the current template scope.

    {% set articleCount = archives|length %}
    <p>本分类共有 {{ articleCount }} 篇文章。</p>
    
  • {% with %}TagIt is mainly used to{% include %}The template fragment passes local variables, or defines temporary variables within a specific logic block. The variables defined are only valid in{% with %}to{% endwith %}。“The variable is only

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

    Here,featuredArticlevalid inwithBlocks are available, avoiding pollution of global variables or unexpected side effects.

By flexibly applying these techniques, you can handle various cases of empty values or undefined variables returned by the database in AnQiCMS templates with ease, making your website not only powerful but also with excellent 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 default values when the variable value is "false" (including)nilempty strings)""or a number0or a boolean valuefalse) and other.default_if_noneThe filter is more strict, it only provides a default when the variable is exactly.nilIt only provides a default value when it is, if the variable is an empty string or other 'false' values, it will not take effect.

    • If you want to provide a common fallback value for all types of 'empty' values (including undefined, empty strings, zero, etc.), usedefault.
    • If you need to distinguishniland other 'empty' values (such as, when a field is explicitly not set versus set to an empty value are two different cases), or when a variable may be a pointer but is not initialized,default_if_noneThis is a more precise choice.
  2. Why do you still see the word 'nil' on the page even though these methods have been used?This usually happens in the following situations:

    • You have useddefaultFilter, but the value is notnila pointer toniltype (e.g.,)*stringa variable of type, with the value ofnil), or an empty struct, etc. At this timedefaultIt may not be considered a 'false' value.
    • You are trying to output directly.nilA variable for the value, but forgot to use.default_if_noneorifA statement to make a judgment. In Go language,nilThe value is usually displayed as 'nil' when directly output in the template.
    • The variable is not truly undefined or empty, but rather some nested field inside it is empty ornilBut you directly accessed the outer variable. At this time, further checks and judgments need to be made on nested fields.
  3. In the loop, besidesemptytag, what else can I do to 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 a specific field of each element within the loop being empty, or if you need to have more fine-grained control over the data in the loop, you can combine their use.ifanddefaultFilter. For example, you can use it again in eachitemloop.{% if item.field %}or{{ item.field|default:"默认值" }}Handle null values for individual elements.In addition, if the element types in the list are complex, consider performing preprocessing on the Go backend code side before passing the data to the template to ensure the integrity and consistency of the data.