How to perform basic conditional judgments in AnQiCMS templates, such as checking if a variable exists?

Calendar 👁️ 59

Mastering Content Wisdom: The Art of Variable Judgment in AnQiCMS Templates

In the world of websites built with AnQiCMS, the template is the stage for content, and how to make the elements on this stage intelligently display according to different conditions is the core skill that every operations expert and developer needs to master.As an enterprise-level content management system based on Go language and supporting syntax similar to Django template engine, AnQiCMS provides intuitive and powerful template tags, among which the most fundamental and commonly used are variable conditional judgments, especially the judgment of whether a variable exists or has a value.

Imagine if your website needs to display an author's avatar on an article detail page, but some articles may not have set one;Or, a product list page where you only want to display the dropdown menu when there are subcategories.These scenarios cannot do without observing the variables. Today, let's delve into how to make elegant basic conditional judgments in the AnQiCMS template, especially how to determine if a variable exists and has a value.


I. Basic Conditional Judgment in AnQiCMS Templates

The template syntax of AnQiCMS follows the style of Django template engine, using conditional judgment{% if ... %}Label pair. It allows us to determine whether to render a specific content block based on the truth or falsity of an expression. A complete conditional judgment structure typically includes{% if %}, optional{% elif %}(else if) and{% else %}, and the final{% endif %}To end the judgment.

For example, a simple judgment might be like this:

{% if archive.Id == 10 %}
    <p>这是文档ID为10的文档的特别内容。</p>
{% else %}
    <p>这不是文档ID为10的文档。</p>
{% endif %}

This structure provides the basic framework for controlling the display of page elements. We can also cleverly use this to determine whether a variable exists or has a value.{% if %}.


Chapter 2: Core Techniques and Practices for Checking Variable Existence and Value

In the AnQiCMS template, determining whether a variable exists or has a value depends mainly on the template engine's understanding of 'truthy' and 'falsy' values. When a variable is defined but its value is an empty string, 0,nilAn empty value, or an empty collection (such as an empty array, empty slice, or empty dictionary), is considered a 'false value' by the template engine; otherwise, it is considered a 'true value'.

1. Directly judge the variable name: The most concise "exists" judgment

The most direct way to determine if a variable exists or has a value is to place it in{% if %}In the label. If the variable exists and is considered a "true" value, the condition is met.

Suppose we are displaying a document and we want to show a thumbnail only if the document is set to display one.ThumbIt will display when this is true:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}" />
{% else %}
    <p>暂无缩略图。</p>
{% endif %}

Here, archive.ThumbIf it is a valid image URL string, it is 'true', and the image will display. Ifarchive.Thumbit is an empty string ornilIt is the 'false value', which will display 'no thumbnail available'. This is a concise and efficient method commonly used in template development.

The same logic also applies to判断数字、布尔值等:

{# 如果 archive.Views(浏览量)大于0,则显示 #}
{% if archive.Views %}
    <span>浏览量:{{ archive.Views }}</span>
{% endif %}

{# 如果 item.IsCurrent(是否当前)为true,则添加active类 #}
<li class="{% if item.IsCurrent %}active{% endif %}">
    <a href="{{ item.Link }}">{{ item.Title }}</a>
</li>

2. Check if the set (list) is empty:{% for ... empty %}elegant use

When we need to judge a set (such asarchiveListorcategoryListWhether the returned list contains an element, besides using{% if collection_name %}AnQiCMS also provides a more elegant and semantically meaningful{% for ... empty %}the structure.

This structure allows you to execute when traversing a collection if the collection is empty{% empty %}The content of the block:

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {% for item in archives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <li>该分类下没有任何文档。</li>
    {% endfor %}
{% endarchiveList %}

This code clearly expresses the logic of 'if there is a document, traverse and display it, otherwise prompt that there is no content', avoiding extra{% if %}judgment, making the code more compact and readable.

3. Use to judge a variable does not exist (negative judgment):{% if not %}

Sometimes, we may need to judge a variableNotwhether it exists orNoneexecute certain operations. At this time, you can add before the variablenotkeywords.

For example, on the article detail page, we often display "Previous" and "Next" links. If the current article does not have a previous or next article, we usually display "None" or do not display the link:

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

{% nextArchive next %}
    <div>
        下一篇:
        {% if not next %}
            <span>没有了</span>
        {% else %}
            <a href="{{ next.Link }}">{{ next.Title }}</a>
        {% endif %}
    </div>
{% endnextArchive %}

{% if not prev %}Will judgeprevWhether the variable is a 'false value' (i.e., does not exist or is empty), thus deciding to display a prompt or the actual link.

4. UsedefaultThe filter provides default values: display judgment.

In addition to controlling the display of content blocks, sometimes we just want to display a preset default text when a variable has no value, rather than controlling the logic of the entire code block. At this point, we can usedefaultfilter.

defaultThe filter will return the default value you specify when the variable is a "false value". Please note that this will not change the rendering logic of the template, it just provides an alternative display content.

<p>作者:{{ archive.Author|default:"佚名" }}</p>
<p>发布日期:{{ stampToDate(archive.CreatedTime, "2006-01-02")|default:"未知日期" }}</p>

In this example, ifarchive.AuthorNo value, the page will display "Anonymous"; ifarchive.CreatedTimeUnable to be formatted (for example, a value of 0 or nil), then display "Unknown Date". This is especially suitable for optional text information that does not affect the core layout of the page.

In addition, there is another.default_if_noneA filter that is stricter, only providing default values when the variable is in Go language.nil(null pointer) and does not provide default values likedefaultSuch also works for empty strings, 0, etc. In most web template scenarios,defaultusually is enough to use.


Third, the application combined with actual scenarios.

You have mastered these basic conditional judgment skills, and you can control the display of content in the AnQiCMS template with ease:

  • **Lazy loading of image resources

Related articles

When encountering difficulties in submitting or displaying anomalies in the AnQiCMS message form, how should it be investigated?

Hello, as an experienced website operation expert, I know that when a message form on a website has problems, whether it is unable to submit or shows an error, it will bring a bad experience to users, and may even lead to the loss of important business leads.For AnQiCMS such an efficient and customizable Go language CMS system, although its underlying architecture is stable and reliable, we may also encounter various unexpected situations in actual operation.

2025-11-06

How to add a checkbox for privacy policy or terms of service in the comment form?

## Enhancing Website Compliance: How to Add a Privacy Policy Checkbox Gracefully to Anqi CMS Contact Form In the digital age, user privacy protection has become a cornerstone that cannot be ignored in website operations.Whether it is to deal with the EU's GDPR or similar regulations in other regions, clearly informing users of the data processing methods and obtaining their consent is an important step in building trust and avoiding risks.

2025-11-06

How to manage and set the `placeholder` text of the AnQiCMS message form through the backend?

In the many details of website operation, the design and management of the message form often reflect the professionalism and user-friendliness of the website.A well-designed feedback form that can effectively collect information and enhance user experience.Among them, the `placeholder` text may seem trivial, but it plays an indispensable role in guiding user input and enhancing the clarity of forms.Today, let's delve deeply into how AnQiCMS (AnQiCMS) achieves unified configuration and optimization of the `placeholder` text for the comment form through its powerful backend management system.

2025-11-06

How to use the `Required` field in AnQiCMS template to generate the HTML5 `required` attribute?

As an experienced website operations expert, I know that building an efficient and user-friendly website not only lies in its rich content, but also in its excellent user experience.In a multitude of content management systems, AnQiCMS stands out with its powerful custom content model and flexible template engine, especially in handling user interactions, such as form submissions, where it can easily meet fine-grained requirements.

2025-11-06

How to use the `{% if ... else ... %}` structure to implement a two-way logic in AnQiCMS templates?

As an experienced website operations expert, I am well aware of the importance of a flexible and powerful content management system for website operations.AnQiCMS leverages its high-performance architecture based on the Go language and Django-like template engine syntax, providing us with great convenience.In daily content operation, we often need to display different content based on different conditions, at this time, it is important to master the conditional judgment structure in AnQiCMS templates, especially `{% if ...else ...It is particularly important.

2025-11-06

In AnQiCMS template, how to handle multiple conditional branches using `{% if ... elif ... else ... %}`?

## The conditional logic in AnQi CMS template: flexible use of `{% if ...elif ...else ...Implement multi-branch controlAnQiCMS (AnQiCMS) with its efficient, customizable features, provides us with powerful content management capabilities.

2025-11-06

What are the specific application scenarios of the negation judgment `{% if not variable %}` in AnQiCMS templates?

In the Anqi CMS template world, efficiently and flexibly displaying content is the key to the success of website operation.We often need to decide the display of page elements based on the existence or not, and the truth or falsity of the status.And the negation judgment like `{% if not variable %}` is a seemingly simple but extremely powerful tool in template development, which can help us build smarter and more user-friendly website interfaces.As an experienced website operations expert, I know that every detail of the template may affect user experience and operational efficiency.

2025-11-06

How does the `if` tag in AnQiCMS template judge whether a numeric variable is `0` or `0.0`?

How to elegantly judge whether a numeric variable is zero in Anqi CMS template?As an experienced website operations expert, I know how important it is to flexibly use the conditional judgment function of templates in daily content management.Especially when dealing with dynamic data, such as product inventory, article views, or price variables of this kind, we often need to determine whether they are "zero" or "0.0", so as to display different content or execute different logic.

2025-11-06