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

In the template world of AnQi CMS, flexibly controlling the display of content is the key to creating an engaging website. Whether it is to display different information based on specific conditions or to efficiently cycle through a large amount of data,ifandforThese tags are essential tools for us. The template engine of AnQiCMS adopts the syntax of Django, making these operations both intuitive and powerful.

UnderstandingifLabel: Conditionally Display Content

ifThe core function of the label is to decide whether to display a certain part of the content based on the conditions you set.This is like setting up a 'bouncer' for your website content, allowing only visitors who meet specific 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:Suppose you want to display an image on the article detail page only when there is a thumbnail image. 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 thumbnail path of the current article toarticlethe variable. IfarticleVariable exists (i.e., the article has a thumbnail),ifIf the condition is true, the image will be displayed.

  • Display content 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 %}
    

    This is assumeduserThe 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 %}
    

    PassHasChildrenProperties, we can intelligently guide users to browse content.

MasterforTags: Implement the cyclic display of content.

forLabels are used to iterate over each element in a collection (such as a list, array) and to execute the same template code for each element.This is very efficient for displaying lists of articles, products, 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 functions of the website is to display 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,archiveListThe tag fetched the latest 10 articles, then.forLoop through these articles and generate a display block for each article.

  • Build a dynamic navigation menu:If your website navigation is multilevel,forLooping with nestedifTags can elegantly 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 menu with sub-menus in a single loop.

  • Handling empty list: forLabels also provide a{% empty %}option that is displayed when the collection in the loop is empty.emptyContent within the block, not nothing displayed.

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

    This greatly improves the user experience and avoids blank pages.

  • UtilizeforloopVariable enhanced control:InforInside the loop,forloopThe object provides a lot of useful information:

    • forloop.Counter: Current iteration count of the loop, starting from 1.
    • forloop.Revcounter: Remaining iteration count in the loop, decreasing from the total number of sets to 1.
    • forloop.First: If it is the first iteration, it is true.
    • forloop.Last: If it is the last iteration, 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 a specific style to the first or last element of a list.

ifandforThe strong combination: Advanced content display

ifandforLabels often work together to achieve more refined content control and display.For example, in a list of articles, you may need to add special tags 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 demonstrates how to dynamically adjust the display style and content of an article while iterating over it in a loop, based on whether the article has a thumbnail and whether it has a "Headline" flag. Filterertruncatechars:80Used to limit the length of descriptions to maintain the cleanliness of the page.

Through these flexible combinations, you can create highly dynamic and user-friendly website interfaces, fully leveraging the potential of the AnQiCMS template engine. Proficient in usingifandforLabel, it will make your content operation strategy more powerful on AnQiCMS platform.


Common Questions (FAQ)

Q1: Inforin the loop,forloop.Counterandforloop.Revcounterdiffer?

A1:forloop.CounterRepresents the number of iterations of the current loop, it starts from1Start incrementing. For example, in a list with 5 elements, the first iteration isforloop.Counter1, 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 to1In the same list of 5 elements, during the first iteration,forloop.RevcounterIt is 5, the second is 4, and it is 1 in the last iteration. You can use this to add different styles or logic to list items.

Q2: How toforIn the loop, judge whether the current element is the last one?

A2: AnQiCMS template engine providesforloop.LastThis boolean variable. When the current iteration is the last element in the set,forloop.Lasthas a value oftrue. You can use it directly in conditional statements, for example:{% if forloop.Last %}这是最后一个元素{% endif %}.

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

A3: For most cases, you can directly place the variable intoifCondition is met. If the variable is an empty string, an empty list (or array), a zero-value number, ornil(empty),ifthe condition is usually evaluated as false (false). For example,{% if my_variable %}willmy_variableNot empty is true. If you want to explicitly judge whether the variable is empty, you can use{% if not my_variable %}. For strings, you can also explicitly compare with an empty string:{% if my_string == "" %}.