How to determine if a variable is empty or execute conditional logic in AnQiCMS templates?

As an experienced website operations expert, I know how crucial precise control of template logic is when building and maintaining an efficient, user-friendly website.Especially when using a content management system like AnQiCMS, which is based on Go language, focuses on performance and flexibility, it is possible to flexibly judge variable states and execute conditional logic according to different situations, which is the cornerstone of ensuring correct content display, avoiding page errors, and enhancing user experience.

The AnQi CMS template engine uses a markup syntax similar to Django, making it easy for operators and developers familiar with web development to quickly get started.It provides intuitive and powerful conditional judgment and loop control capabilities, helping us easily handle various content display scenarios.Today, let's delve into how to judge whether a variable is empty or execute complex conditional logic in the AnQiCMS template.


Basic conditional judgment in AnQiCMS template:ifThe clever use of tags

In the world of AnQiCMS templates, the most core conditional judgment tool is undoubtedly{% if %}Label. Its syntax is concise and powerful, allowing us to decide whether to render a specific content block based on the boolean value of a variable.

A variable in the AnQiCMS template engine is when it isnil(empty value),false(boolean false), number0an empty string""Or when an empty collection (such as an empty array, empty slice, empty dictionary/map) is encountered, it will be{% if %}labeled as 'falsy'. This means that we do not need to explicitly write{% if variable == nil %}or{% if variable == "" %}directly{% if variable %}Can elegantly judge whether a variable has actual content.

Let's look at some common examples to understand this:

  • Check if a string is empty:

    {% if archive.Title %}
      <h1>{{ archive.Title }}</h1>
    {% else %}
      <h1>暂无标题</h1>
    {% endif %}
    

    Here, ifarchive.TitleIf there is any non-empty string value, the title will be displayed; otherwise, it will display 'No title available'.

  • Determine if the list or set is empty:Assumecategory.ImagesIt is a list of images:

    {% if category.Images %}
      <div class="banner">
          {% for img in category.Images %}
              <img src="{{ img }}" alt="分类图片">
          {% endfor %}
      </div>
    {% else %}
      <p>此分类暂无图片展示。</p>
    {% endif %}
    

    Ifcategory.ImagesContains an image, which will be rendered; if it is an empty list, a prompt message will be displayed.

  • Evaluate boolean or number:For example, obtain whether the website is in a closed state from the background system settings:

    {% if system.SiteStatus == 0 %} {# 假设0代表开启,非0代表闭站 #}
      <p>网站正在正常运行。</p>
    {% else %}
      <p>网站已暂停访问:{{ system.SiteCloseTips }}</p>
    {% endif %}
    

    We can also take advantage of{% elif %}(else if) and{% else %}To build a more complex conditional chain to deal with multiple business logic:

    {% if user.IsVIP %}
      <p>欢迎VIP会员,尊享专属内容!</p>
    {% elif user.TotalReward > 100 %}
      <p>您的累计收益已超过100元,快升级VIP解锁更多权益!</p>
    {% else %}
      <p>您是普通会员,查看更多精彩内容!</p>
    {% endif %}
    

Gracefully handle empty collections:forrepeatedlyemptyTag

When dealing with lists, arrays, and other collection data types, we often need to determine if they contain elements.If the set is empty, we may need to display a "no content" prompt.AnQiCMS's template engine is{% for %}Loop provides a very practical{% empty %}Tags make the processing of this scene particularly concise and elegant.

For example, when we need to display a list of related articles of a document:

{% archiveList archives with type="related" limit="5" %}
    <div class="related-articles">
        <h3>相关推荐</h3>
        <ul>
            {% for item in archives %}
                <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
            {% empty %}
                <li>暂无相关文章推荐。</li>
            {% endfor %}
        </ul>
    </div>
{% endarchiveList %}

IfarchivesThe list contains articles,{% for %}The loop will traverse normally and display them; if the list is empty,{% empty %}the content within the tag will be rendered, perfectly avoiding extra{% if archives %}Judgment. This not only makes the template code more concise, but also improves the robustness of the website.

Smart use of filters: to provide default values for variables or to make advanced judgments.

AnQiCMS's template filters are powerful tools for handling variables and formatting output, some of which are particularly useful for determining variable states or providing alternative content.

  1. defaultanddefault_if_noneFilter: Provide alternative contentWhen a variable may be empty or not exist, we would like to provide a default value instead of having the page display blank or error.

    • defaultThe filter provides a default value when the variable is evaluated as 'false' (such as an empty string, 0, false).
    • default_if_noneThe filter is more strict, only when the variable is actuallynil(or in Go language)nilType) provides a default value only when specified, and does not affect empty strings or 0.

    For example, show the article description, or display "Click to view details" if it is empty:

    <p>{{ archive.Description|default:"点击查看详情" }}</p>
    

    Ifarchive.DescriptionIs an empty string ornilIt will display "Click to view details".

    Assumeuser.PhoneMay be anilfield, not an empty string:

    <p>联系电话:{{ user.Phone|default_if_none:"未提供" }}</p>
    
  2. lengthFilter: Check the length of a string or collection lengthThe filter can conveniently obtain the number of characters in a string or the number of elements in a collection (such as an array, slice, or map).This is very useful when it is necessary to judge the length precisely rather than just judge 'true or false'.

    {% if archive.Content|length > 100 %}
        <p>文章内容很长,请耐心阅读。</p>
    {% else %}
        <p>文章内容较短。</p>
    {% endif %}
    

    Here, we judge whether the length of the article content string exceeds 100 characters.

  3. containFilter: Determine if it contains specific content.If you need to determine whether a string contains a substring or an array contains an element,containThe filter can be used.

    {% if archive.Content|contain:"SEO" %}
        <p class="tag">本文包含SEO相关内容。</p>
    {% endif %}
    

    If the article content contains the word 'SEO', a corresponding prompt will be displayed.

  4. yesnoFilter: Semantic boolean output yesnoThe filter can convert boolean values or variables that can be evaluated as boolean values into more semantically meaningful text outputs.It can accept up to three parameters, corresponding to the display text for 'true', 'false', and 'unknown/nil'.

    <p>审核状态:{{ archive.Status|yesno:"已发布,待审核,未设置" }}</p>
    

    Ifarchive.StatusWithtrueFor example (1), display 'Published'; forfalseFor example 0, it shows "Pending review"; if it isnil, it shows "Not set".

Practical exercise: Comprehensive use of judgment logic

Let us demonstrate how to comprehensively apply these judgment logic through a slightly more complex scenario. Suppose we are building a product detail page, where we need to display content based on different product attributes:

`twig

<h1>{{ archive.Title|default:"产品名称待定" }}</h1>

{%- if archive.Logo %}
    <div class="product-image">
        <img src="{{ archive.Logo }}" alt="{{ archive.Title }}">
    </div>
{%- elif archive.Images %}
    <div class="product-gallery">
        {%- for img in archive.Images %}
            <img src="{{ img }}" alt="产品图">
        {%- empty %}
            <p>产品图片正在上传中...</p>
        {%- endfor %}
    </div>
{%- else %}
    <div class="no-image-placeholder">
        <p>暂无产品图片。</p>
    </div>
{%- endif %}

<div class="product-