How to skip certain items in the `for` loop of the AnQiCMS template based on specific conditions?

Calendar 78

In AnQiCMS template development, we often need to display a series of contents, such as article lists, product lists, or navigation menus.But often, we do not want to display all the data at once, but rather hope to skip a part of it cleverly based on certain conditions, so that the final content displayed is more accurate and meets the user's needs.AnQiCMS uses a syntax similar to the Django template engine, which provides a powerful and flexible tool for us to implement this conditional skipping.

To implementforIn a loop, to skip the display of certain items based on specific conditions, the most core tool isifa logical judgment tag. By wrapping the HTML segment that needs to be displayed with conditionsifIn the tag, we can easily control the visibility of each item.

Core mechanism:iflogical judgment tag

Imagine you are iterating over an article list and you want to display only those articles that are not marked as "recommended". At this point, you can make use of{% if ... %}the structure. AnQiCMS'sarchiveListEach article (or other model content) obtained by the label usually has oneFlagfield to mark its recommended attributes, such ascrepresenting a recommendation. If aitem(the current item in the loop) of theFlagField is not equalcOnly then do we display it:

{% archiveList archives with type="list" limit="10" showFlag=true %}
    {% for item in archives %}
        {% if item.Flag != "c" %}
            <li class="article-item">
                <a href="{{ item.Link }}">
                    <h3>{{ item.Title }}</h3>
                    <p>{{ item.Description }}</p>
                </a>
            </li>
        {% endif %}
    {% endfor %}
{% endarchiveList %}

In the above example,{% if item.Flag != "c" %}This line of code plays a key role. It checks the currentitemofFlagwhether it is not equal to"c". If the condition is true, then<li>The content inside the tag will be rendered; if the condition is false (i.e.Flagequals"c"), then the entire<li>and its content will be skipped and will not appear on the final page.

except!=(Not equal), you can also use other comparison operators:

  • ==(Equal to)
  • >(Greater than)
  • <(Less than)
  • >=(greater than or equal to)
  • <=(less than or equal to)
  • and(Logical AND)
  • or(Logical OR)
  • not(Logical NOT)
  • in(Contains)

These operators allow you to build very complex conditions.

Combine content attributes with custom fields

The flexibility of AnQiCMS lies in its powerful content model and custom field features.This means you can set skip conditions based on any built-in or custom field of an article, product, or single page.

For example, if you want to skip articles that do not have a thumbnail set, you can do this:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        {% if item.Thumb %} {# 如果 item.Thumb 存在且不为空,则为 True #}
            <li class="article-with-thumb">
                <a href="{{ item.Link }}">
                    <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
                    <h3>{{ item.Title }}</h3>
                </a>
            </li>
        {% endif %}
    {% endfor %}
{% endarchiveList %}

here,{% if item.Thumb %}Will checkitem.ThumbDoes the field have a value. If it does, show this item; if not, skip. Conversely, if you want to display only those articles without thumbnails, you can use{% if not item.Thumb %}.

For a custom field, assume you have added a field namedEditorRecommendA boolean field used to mark articles recommended by the editor. Then, you can display all non-editor recommended articles like this:

{% archiveList archives with type="list" moduleId="1" limit="10" %}
    {% for item in archives %}
        {% if not item.EditorRecommend %} {# 假设 EditorRecommend 是一个布尔值 #}
            <li class="normal-article">
                <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
                <p>{{ item.Description }}</p>
            </li>
        {% endif %}
    {% endfor %}
{% endarchiveList %}

More flexible filtering: use filters

AnQiCMS template engine also supports various filters, which can provide more advanced logic in conditional judgments. For example,containThe filter can determine if a string contains a substring, which is very useful when skipping based on keywords.

Suppose you have a single-page list, but you don't want to display any page with a title containing "Privacy Policy" in the main navigation:

{% pageList pages %}
    {% for item in pages %}
        {% if not item.Title|contain:"隐私政策" %}
            <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
        {% endif %}
    {% endfor %}
{% endpageList %}

here,item.Title|contain:"隐私政策"It will check if the title of the current page contains the keyword "Privacy Policy". If it does,notthe operator will change it tofalse, thus skipping the item.

Another example is usinglengthA filter to determine the length of content. For example, you only want to display those briefDescription) articles that exceed 50 characters:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        {% if item.Description|length > 50 %}
            <li class="detailed-description-article">
                <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
                <p>{{ item.Description }}</p>
            </li>
        {% endif %}
    {% endfor %}
{% endarchiveList %}

Practical case: common skip scenarios

Let's take a look at several common application scenarios:

  1. Hide navigation items with specific IDs:If you have a navigation menu with an ID of5The navigation item is temporary or should not be displayed in the current template:

    {% navList navs %}
        {% for item in navs %}
            {% if item.Id != 5 %}
                <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
            {% endif %}
        {% endfor %}
    {% endnavList %}
    
  2. Skip parent categories without subcategories:When displaying the category list, sometimes we only want to display those category items that contain child categories, or vice versa, only display leaf categories: “`twig {% categoryList categories with moduleId=“1” parentId=“0” %}

    {% for item in categories %}
        {% if item.HasChildren %} {# 只显示有子分类的项 #}
            <li><a href="{{ item.Link }}">{{ item.
    

Related articles

How to implement the `cycle` tag to alternate the display of different styles or data in AnQiCMS templates?

AnQiCMS provides many practical tags for template development, making content display more flexible and efficient.Among them, the `cycle` tag is such a clever tool that it can help us achieve the alternation of data or styles in loops, making the page content more dynamic and visually attractive. ### Understanding the `cycle` tag: Sequence controller in loops In web design, we often encounter situations where we need to apply different styles to repeating elements or display different types of data in a specific order. For example

2025-11-09

How to judge whether the current item is the first or last item in the `for` loop in AnQiCMS template?

In AnQiCMS template development, we often encounter situations where we need to display data in a list loop, such as article lists, product categories, navigation menus, etc.In these loops, sometimes we need to treat the first or last item in the list specially, such as adding unique CSS styles, displaying different content, or cleverly handling the separators between list items.AnQiCMS uses a syntax similar to the Django template engine, providing us with a very intuitive and powerful tool to solve these common template logic problems.### Core Mechanism

2025-11-09

How to check if the article content in the AnQiCMS template contains specific keywords and display conditions based on this?

In website content operation, we often need to flexibly adjust the display of the page according to the actual content of the article.For example, if an article mentions a specific product or event, we may want to highlight related purchase links or promotional information on the page;If the content of the article involves sensitive topics, it may be necessary to add additional disclaimers.This requirement for conditional display based on article content can be fully realized in the AnQiCMS template.AnQi CMS uses a template engine syntax similar to Django

2025-11-09

How to control the automatic escaping of HTML tags with the `autoescape` tag in AnQiCMS templates?

In the AnQiCMS template system, our daily content display core is inseparable from the handling of HTML tags.To ensure the security of the website, AnQiCMS defaults to automatically escaping variables output in templates.This mechanism effectively prevents the injection of malicious code, such as common cross-site scripting attacks (XSS).However, in some scenarios, we may need to display rich text content that includes HTML tags, at this point we need to understand how to flexibly control this automatic escaping function.### Automatically Escaped

2025-11-09

How to judge whether a custom field exists in the AnQiCMS template and conditionally render according to its value?

In AnQiCMS template development, flexibly displaying content is the key to improving user experience and website professionalism.Among them, judging custom fields and rendering conditions based on their values is an indispensable skill to achieve this goal.In this way, you can ensure the precise display of page content, avoid displaying empty values, or dynamically adjust the page layout and functionality based on specific data.### Understanding AnQiCMS Custom Fields and Their Retrieval Methods in Templates AnQiCMS is a powerful content management system

2025-11-09

How to determine if the `Content` field of the document is empty using the `archiveDetail` tag and display alternative content?

How can you elegantly handle the case where the document content is empty in AnQi CMS?During the operation of the website, we often publish various types of documents, which contain important information.However, sometimes for various reasons, such as the content is still in draft stage, data is missing during import, or simply some documents are only titled without detailed text, we may encounter the situation where the `Content` field of the document is empty.If the template does not perform any processing when rendering these document detail pages, the user may see a blank page area, which not only affects user experience

2025-11-09

How to safely embed third-party statistics or advertising JS code in AnQiCMS templates?

In website operation, we often need to rely on third-party statistical tools to analyze visitor behavior, or to generate income through advertising platforms.Embed these third-party JavaScript (JS) codes securely and efficiently into website templates is a skill that every website operator needs to master.For those using AnQiCMS, understanding its template mechanism and built-in features can help us complete this task more securely.AnQiCMS is an enterprise-level content management system developed based on the Go language, which has always paid close attention to performance and security in its initial design

2025-11-09

How to ensure the correct setting of the `hreflang` tag in the `languages` label of the AnQiCMS multilingual site?

Today, with the deepening of globalization, many enterprises and content operators need to provide customized content for users of different languages or regions.To ensure that these multilingual versions can be correctly identified and displayed to target users, the proper setting of the `hreflang` tag is particularly important.For friends using AnQiCMS to build multilingual websites, the built-in `languages` tag is the powerful tool to solve this problem.Understanding the importance of the `hreflang` tag To delve deeper into

2025-11-09