How to use `if` and `for` tags to implement conditional display and loop display of content in AnQiCMS templates?

Calendar 👁️ 66

In the world of Anqi CMS templates, flexibly controlling the display of content is the key to creating an engaging website. Whether it's displaying different information based on specific conditions or efficiently looping through a large amount of data,ifandforThese tags are indispensable tools. AnQiCMS's template engine adopts Django's syntax, making these operations intuitive and powerful.

UnderstandingifLabel: Display content under certain conditions

ifThe core function of the label is to decide whether to display a part of the content based on the conditions you set.This is like setting up a 'gatekeeper' for your website content, allowing only visitors who meet certain conditions to enter.

Its basic syntax structure is very concise, usually like this:

{% if 条件表达式 %}
    <!-- 条件为真时显示的内容 -->
{% endif %}

When you need to handle more complex logic, you can introduceelseandelif(else if abbreviation) to expand:

{% if 第一个条件 %}
    <!-- 第一个条件为真时显示的内容 -->
{% elif 第二个条件 %}
    <!-- 第二个条件为真时显示的内容 -->
{% else %}
    <!-- 所有条件都不满足时显示的内容 -->
{% endif %}

Actual application scenarios:

  • Show/hide specific information:Assuming you want to display an image on the article detail page only when the article has a thumbnail, you can write it like this:

    {% archiveDetail article with name="Thumb" %}
    {% if article %}
        <img src="{{ article }}" alt="文章缩略图" />
    {% else %}
        <p>此文章暂无缩略图。</p>
    {% endif %}
    

    here,{% archiveDetail article with name="Thumb" %}The tag assigns the current article's thumbnail path toarticlea variable. IfarticleThe variable exists (i.e., the article has a thumbnail),ifIf the condition is true, the image will be displayed.

  • Content is displayed based on the user's status:If you have a membership system, you can display different content based on whether the user is logged in or their VIP level.

    {% if user.IsLoggedIn %}
        <p>欢迎回来,{{ user.UserName }}!</p>
        {% if user.IsVIP %}
            <p>您是尊贵的VIP会员,可享受专属内容。</p>
        {% else %}
            <p>升级VIP获取更多权益。</p>
        {% endif %}
    {% else %}
        <p>请登录或注册以获取完整体验。</p>
    {% endif %}
    

    AssuminguserThe object contains the user's login status and VIP information.

  • Category or page attribute judgment:You may need to decide whether to display the subcategory list or directly display the article list based on whether the current category has subcategories.

    {% categoryDetail currentCategory with name="HasChildren" %}
    {% if currentCategory %}
        <p>本分类包含子分类,请选择:</p>
        {% categoryList subCategories with parentId=currentCategory.Id %}
            {% for subCat in subCategories %}
                <a href="{{ subCat.Link }}">{{ subCat.Title }}</a>
            {% endfor %}
        {% endcategoryList %}
    {% else %}
        <p>本分类暂无子分类,显示文章列表:</p>
        {% archiveList archives with categoryId=currentCategory.Id %}
            <!-- 文章列表内容 -->
        {% endarchiveList %}
    {% endif %}
    

    ByHasChildrenProperties, we can intelligently guide users to browse content.

MasterforTags: To achieve the loop display of content

forThe tag is used to iterate over each element of a collection (such as a list or array) and execute the same template code for each element.This is very efficient for displaying article lists, product lists, navigation menus, and other repetitive content.

The basic syntax is as follows:

{% for 变量名 in 集合 %}
    <!-- 针对集合中每个元素显示的内容 -->
{% endfor %}

Actual application scenarios:

  • Display the list of articles:One of the most common features of a website is the display of article lists.

    {% archiveList articles with type="list" limit="10" %}
        {% for article in articles %}
            <div class="article-item">
                <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
                <p>{{ article.Description }}</p>
                <span>发布日期:{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
            </div>
        {% endfor %}
    {% endarchiveList %}
    

    here,archiveListTags have retrieved the latest 10 articles, then.forLoop through these articles to generate a display block for each article.

  • Build a dynamic navigation menu:If your website navigation is multi-level,forcombined with nested loops,ifthe tags can beautifully achieve this.

    {% navList mainNavs %}
        <ul>
            {% for nav in mainNavs %}
                <li>
                    <a href="{{ nav.Link }}">{{ nav.Title }}</a>
                    {% if nav.NavList %} {# 如果有子导航 #}
                        <ul>
                            {% for subNav in nav.NavList %}
                                <li><a href="{{ subNav.Link }}">{{ subNav.Title }}</a></li>
                            {% endfor %}
                        </ul>
                    {% endif %}
                </li>
            {% endfor %}
        </ul>
    {% endnavList %}
    

    This demonstrates how to build a navigation with sub-menus using a single loop.

  • Handle empty list: forthe tag also provides a{% empty %}Options will be displayed when the loop collection is emptyemptyThe content within the block will be displayed instead of nothing.

    {% archiveList articles with type="list" categoryId="999" limit="5" %} {# 假设这个分类下没有文章 #}
        {% for article in articles %}
            <!-- 文章内容 -->
        {% empty %}
            <p>这个分类下暂时没有文章。</p>
        {% endfor %}
    {% endarchiveList %}
    

    This greatly enhances the user experience, avoiding a blank page.

  • UtilizeforloopVariable enhanced control:Inforinside the loop,forloopThe object provides many useful information:

    • forloop.Counter: The current iteration number of the loop, starting from 1.
    • forloop.Revcounter: The remaining iteration number in the loop, decreasing from the total number of the set to 1.
    • forloop.First: If the current iteration is the first, it is true.
    • forloop.Last: If the current iteration is the last, it is true.
    {% archiveList articles with type="list" limit="3" %}
        {% for article in articles %}
            <div class="article-item {% if forloop.First %}first-item{% elif forloop.Last %}last-item{% endif %}">
                <p>这是第 {{ forloop.Counter }} 篇文章,还剩 {{ forloop.Revcounter }} 篇。</p>
                <h3>{{ article.Title }}</h3>
            </div>
        {% endfor %}
    {% endarchiveList %}
    

    This can be used to add specific styles to the first or last element of the list.

ifandforAdvanced content display: A powerful combination.

ifandforLabels often collaborate to achieve more refined content control and display.For example, in an article list, you may need to add special markers to articles with images or specific symbols.

{% archiveList articles with type="list" limit="5" showFlag=true %} {# 注意这里设置了 showFlag=true #}
    {% for article in articles %}
        <div class="news-card">
            {% if article.Thumb %} {# 检查是否有缩略图 #}
                <img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="news-thumb">
            {% endif %}

            <div class="news-content">
                {% if article.Flag and "h" in article.Flag %} {# 检查是否有“头条”标志 #}
                    <span class="badge hot-news">头条</span>
                {% endif %}
                <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
                <p>{{ article.Description|truncatechars:80 }}</p> {# 使用过滤器截断描述 #}
                <span class="date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
            </div>
        </div>
    {% empty %}
        <p>暂时没有新闻内容。</p>
    {% endfor %}
{% endarchiveList %}

This example shows how to dynamically adjust the display style and content of articles while looping through them, based on whether they have a thumbnail or a "headline" flag. Filtertruncatechars:80It is also used to limit the length of the description, keeping the page tidy.

By using these flexible combinations, you can create highly dynamic and user-friendly website interfaces, fully leveraging the potential of the AnQiCMS template engine. Proficient in usingifandforThe tag will enable your content operation strategy to soar on the AnQiCMS platform.


Frequently Asked Questions (FAQ)

Q1: Atforthe loop,forloop.Counterandforloop.RevcounterWhat's different?

A1:forloop.CounterRepresents the current iteration count of the loop, it starts from1Start incrementing. For example, in a list of 5 elements, in the first iterationforloop.CounterIt is 1, the second is 2, and so on.forloop.RevcounterIt represents the remaining number of iterations in the current loop (including this one), which starts from the total number of the set and decrements to1. In the same 5-element list, during the first iteration,forloop.RevcounterIt's 5, the second time is 4, and the last iteration is 1. You can use these to add different styles or logic to list items.

Q2: How toforAre you checking if the current element is the last one in the loop?

A2: AnQiCMS template engine providesforloop.LastThis boolean variable. When the current iteration is the last element of the collection,forloop.LastThe value istrueYou can use it directly in conditional statements, such as:{% if forloop.Last %}这是最后一个元素{% endif %}.

Q3: I want toifHow to check if a variable (such as a string or list) is empty?

A3: For most cases, simply place the variable intoifAs long as the condition is met. If the variable is an empty string, an empty list (or array), or zero-valued numbers ornil(empty),ifThe condition is usually evaluated as false (false). For example,{% if my_variable %}It willmy_variableTrue when not empty. If you want to explicitly determine if a variable is empty, you can use{% if not my_variable %}. For strings, you can also explicitly compare with an empty string:{% if my_string == "" %}.

Related articles

How `tdk` tags can dynamically generate and optimize SEO-related Title, Keywords, and Description for each page?

In modern website operation, the importance of Search Engine Optimization (SEO) is self-evident, and the page title (Title), keywords (Keywords), and description (Description), which we commonly refer to as TDK, are the "business card" of the website content on the Search Engine Results Page (SERP).They not only directly affect the click-through rate of the page, but are also key factors for search engines to understand the content of the page and rank it.AnQiCMS (AnQiCMS) fully understands the significance of TDK for SEO, and therefore in the system design

2025-11-08

How to dynamically fetch and display the global settings and contact information of the website using the `system` and `contact` tags?

In AnQi CMS, the global settings and contact information are the basic information that constitutes the important facade of the website.This information must be displayed accurately to visitors, and more importantly, it should be able to be updated and managed flexibly and conveniently without frequent modifications to the template code.AnQi CMS provides these two powerful tags, `system` and `contact`, allowing website operators to easily achieve dynamic acquisition and display of this information.

2025-11-08

How does the `pagination` tag add and control pagination display for document lists to enhance user experience?

When building a website, as the amount of content grows, the document list page becomes long, which not only affects the page loading speed but also makes it difficult for visitors to find the information they need efficiently.At this time, adding pagination to the document list becomes a key factor in improving user experience.AnQiCMS provides a powerful `pagination` tag, combined with the document list tag `archiveList`, it can easily achieve this goal, making your website content display more professional and more user-friendly.

2025-11-08

How to automatically generate and display the `breadcrumb` tag showing the user's current location in the breadcrumb navigation?

During website browsing, you may often see a line of text links at the top of the page or above the content area, like breadcrumbs, indicating your current position in the website and the path to get here.This is what we commonly call 'Breadcrumb Navigation'.It can not only help users quickly understand their hierarchical structure on the website, avoid getting lost, but also improve the usability of the website and play a positive role in search engine optimization (SEO).For AnQiCMS users, implementing such a feature is very simple and efficient

2025-11-08

How to use the `stampToDate` tag to format timestamps into a friendly date format to display content publication time?

During the operation of the website, the publication time of the content is an important part of conveying information to visitors.A clear and readable date format not only enhances user experience but also makes the website look more professional and timely.In AnQiCMS, the content publish time is usually stored in the form of a series of numbers (i.e., a timestamp).How can we convert these numbers into the familiar 'year-month-day' or 'month/day time:minute' formats that we are accustomed to?AnQiCMS provides us with a very convenient template tag: `stampToDate`.

2025-11-08

How to define temporary variables with the `with` tag in a template to better control content display logic?

When developing website templates in AnQiCMS, we often need to handle various data and decide the display mode of the content according to these data.With the complexity of website functions, the logic in the templates sometimes becomes difficult to understand and maintain.At this point, mastering some advanced template tag usage is particularly important, and the `with` tag is one of the practical tools that can significantly improve the readability and control of the template.### The `with` tag: A tool for defining temporary variables in templates The `with` tag allows us to define temporary variables within a specific area of the template

2025-11-08

How to correctly insert mathematical formulas and flowcharts in a Markdown editor and ensure they display normally on the web?

In content creation, especially in fields involving technology, science, or complex concepts, we often need to insert mathematical formulas or draw flowcharts to assist in explanation.The Markdown editor of AnQiCMS (AnQiCMS) has provided us with great convenience, allowing these complex elements to be input in a concise text form and presented elegantly on the web.How should we operate specifically to ensure that the content is displayed correctly?Firstly, make sure that your safety CMS system has enabled the Markdown editor.

2025-11-08

How does the search engine link push feature help new documents be indexed and displayed in search results quickly?

On the day of content release, how can your meticulously crafted website content be quickly discovered and indexed by search engines, which is a focus for every content operator.A newly released article or product page, if it can appear quickly in the search results, it will undoubtedly seize the initiative and bring valuable early traffic.AnQiCMS (AnQiCMS) fully understands this need and has specially provided a search engine link push feature to help your new document reach the search engine as quickly as possible, thereby speeding up indexing and display.Why is it important to be indexed quickly?

2025-11-08