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

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 == "" %}.