How to use `if` judgment in AnQiCMS template to prevent rendering errors caused by undefined variables?

Governance Anqi CMS template: Make full use ofifSentences, say goodbye to undefined variable rendering errors!

As a senior website operation expert, I fully understand the importance of a stable and efficient website template for user experience and operational efficiency.AnQiCMS (AnQiCMS) provides strong support for content management with its efficient architecture based on the Go language and a flexible Django-like template engine.However, even the most excellent system may cause rendering errors due to minor omissions in the template, the most common of which is accessing undefined variables.ifJudgment, thoroughly solve this annoying problem.

In website template development, data is dynamic, and often, the data we obtain from the background may not always exist, or a field may occasionally be a null value.If the template code attempts to render a non-existent or empty variable directly, it may cause the page to display errors, and in severe cases, it may even lead to the entire page crashing, which is undoubtedly a huge killer of user experience.ifLogical judgment label, providing us with a solid defense.

Understanding the AnQiCMS template in.ifJudgment

AnQiCMS's template syntax is highly similar to Django's template engine, its conditional judgment tags are defined using single curly braces and percent signs, and an end tag is required{% endif %}Pairs appear. The most basicifThe judgment structure is as follows:

{% if 条件 %}
    <!-- 当条件为真时渲染的内容 -->
{% endif %}

The key here is the evaluation of "condition". In AnQiCMS templates,ifthe conditional judgment of statements is very flexible and intelligent:

  • Variable exists and is not emptyIf a variable is defined, and its value is notnilAn empty string ("")、数字0, an empty array ([]) or an empty object ({}), the condition is considered to be "true" (true).
  • The variable does not exist or is empty: Conversely, if the variable is not defined, or its value isnil、空字符串、数字0, an empty array or an empty object, then the condition is considered to be “false” (false).

This means, we don't need to explicitly check if the variable existsnilornulla simple{% if 变量名 %}and it's done!

Scenario one: Ensure the variable exists before rendering

Imagine that your website header needs to display a Logo, the URL of which is obtained from the system settings. But if the operations personnel forget to upload the Logo, or if the Logo is not required to be displayed on a specific page, render it directly<img>The label may cause an emptysrcproperty, or even worse, a page error.

At this point, we can use it like thisifJudgment:

{% system siteLogo with name="SiteLogo" %}
{% if siteLogo %}
    <a href="/">
        <img src="{{ siteLogo }}" alt="网站Logo">
    </a>
{% else %}
    <a href="/">
        <h1>{% system with name="SiteName" %}</h1> <!-- 如果没有Logo,则显示网站名称 -->
    </a>
{% endif %}

In this code, we first attempt to getSiteLogoand assign it tositeLogothe variable. Then,{% if siteLogo %}will checksiteLogoIs it present and not empty. If the Logo image URL exists, then render<img>Label; otherwise, it will gracefully fallback to displaying the website name, ensuring the integrity and beauty of the page structure.

Scenario two: handling list data, avoiding empty loop sets.

When displaying content such as article lists, product lists, or friend links, we often useforHowever, if no content is entered in the background, or the query results are empty, directly looping over an empty set may cause the template to render blank or report an error.

a typicalarchiveListThe label usage scenarios of (Document list) are as follows:

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {% if archives %}
        <ul>
        {% for item in archives %}
            <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>抱歉,当前分类下还没有任何内容。</p>
    {% endif %}
{% endarchiveList %}

Here,{% if archives %}JudgedarchivesIs this list empty. If the list has data, it will be traversed normally and displayed; if the list is empty, it will display a friendly prompt message.

Tip:For list iteration, AnQiCMS also provides a more concise{% for ... empty %}structure, which can automatically handle the case of an empty list, making the code more elegant:

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    <ul>
    {% for item in archives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <li>抱歉,当前分类下还没有任何内容。</li>
    {% endfor %}
    </ul>
{% endarchiveList %}

Scene three: Render content based on specific conditions (elifWithelse)

In some cases, you may need to render different content based on different variable values, or provide multi-level backup solutions. At this time, elif(else if) andelseit can be very useful.

For example, you may want to display different styles or hints based on the recommended attributes of the article (Flag) to show different styles or hints:

{% archiveDetail archiveDetailData with name="Flag" %}
{% if "h" in archiveDetailData %} {# 判断是否包含头条属性 #}
    <span class="badge badge-primary">头条</span>
{% elif "c" in archiveDetailData %} {# 判断是否包含推荐属性 #}
    <span class="badge badge-info">推荐</span>
{% else %}
    <span class="badge badge-secondary">普通</span>
{% endif %}

This code will be executed according to the article'sFlagProperties whether it includes "h" (headlines) or "c" (recommendations) to display different tags.If neither contains, it is displayed as "Common".This multi-level judgment mechanism makes the logic expression of the template more refined.

**Practice and Reflection

  1. Active defense instead of passive repairEnglish: When developing templates, always assume that some data may be missing. Before referencing any variables that may be empty, first checkifEnglish: Develop good coding habits.
  2. Use wiselydefaultFilterFor simple text or numbers, if it is only to provide a default value rather than render a complex structure,defaultthe filter will be a simpler choice. For example:{{ archive.Author|default:"佚名" }}. It complementsifthe judgment is complementary rather than substitute.
  3. Keep the template logic clear: AlthoughifThe template is very powerful, but excessive nesting or complex conditions will reduce the readability of the template. Try to place complex data processing logic on the backend, and the template is only responsible for displaying data.
  4. Combine document review: AnQiCMS provides detailed documentation of tags and filters (such asdesign-tag.md/tag-if.mdetc.). When you are unsure of the type of a variable or itsifWhen the performance under conditions needs to be checked, referring to the official documentation is the most efficient way.

By proficiently using the AnQiCMS templates,ifDetermine, you will be able to build more robust, fault-tolerant website templates, effectively preventing rendering errors caused by undefined variables, thereby providing a more stable, higher-quality user experience.


Common Questions (FAQ)

1. Why does my page display "Undefined variable" or a similar error, even though I am sure that this variable should have a value in some cases?

This usually happens when your template code tries to access something that doesn't exist in the current contextit really doesn't existorThe value isnil/emptyWhen a variable is.Even if this variable has a value on other pages or in the scene you expect, it may still be missing in the current specific rendering request.{{ category.Title }}, but the current page is not a category page, or the article doesn't have associated categories,categoryThe variable is naturally undefined. Use{% if category %}or{% if category.Title %}to make a judgment, which can avoid such errors.

2.{% if 变量 %}and{{ 变量|default:"默认值" }}What is the difference between these two ways of handling, and how should I choose?

  • {% if 变量 %}is more suitable for useRender control structures or content blocks. When a variable does not exist or is empty, you may want to render the entire HTML element (such as<div>/<img>/<ul>)are not rendered, or render a completely different fallback content block. For example, ifLogodoes not exist, you may not want<img>to appear, but instead display text.
  • {{ 变量|default:"默认值" }}is more suitable for useProvide inline, simple alternative text or values.When the variable is missing, you just want to use a simple default value to fill in, rather than changing the entire page layout.For example, if the author field of the article is empty, use 'Anonymous' instead of hiding the entire author information line.

You can choose the simplest and most efficient method according to your specific needs, and both are often combined to achieve **effect.**

3.ifCan you distinguish whether a variable is completely undefined or just an empty string or 0?

In AnQiCMSifJudgment logic