How to use logical tags like `if` and `for` in templates to control conditional and repeated display of content?

In website content management, displaying dynamic and diverse content is the key to improving user experience and website attractiveness.AnQiCMS (AnQiCMS) provides a powerful template system, drawing on the syntax of the Django template engine, allowing you to easily control the display of content through logical tags. Among them,ifTags are used for conditional judgments, andforTags are used for looping, they are the foundation for building flexible and varied pages.

Flexible conditional judgment:ifThe magic of logical tags

ifTags allow you to decide which content should be displayed and which should be hidden on the page based on specific conditions. This makes content display more intelligent and adaptable to various business logic.

BasicifThe syntax is very intuitive:

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

For example, you may want to display images only when the document contains thumbnails:

{% if item.Thumb %}
    <img src="{{item.Thumb}}" alt="{{item.Title}}">
{% endif %}

When your business logic needs to handle multiple possibilities, you can use:elif(else if abbreviation) andelseThe clause:

{% if 条件1 %}
    <!-- 当条件1为真时显示的内容 -->
{% elif 条件2 %}
    <!-- 当条件1为假且条件2为真时显示的内容 -->
{% else %}
    <!-- 当所有条件都为假时显示的内容 -->
{% endif %}

A common application scenario is to decide on displaying different content based on whether the category has subcategories, such as in the navigation menu:

{% if item.HasChildren %}
    <!-- 显示子分类列表 -->
    <ul>
        {% categoryList subCategories with parentId=item.Id %}
            {% for inner in subCategories %}
                <li><a href="{{inner.Link}}">{{inner.Title}}</a></li>
            {% endfor %}
        {% endcategoryList %}
    </ul>
{% else %}
    <!-- 显示该分类下的文档列表 -->
    <p>该分类下暂无子分类,点击查看文档。</p>
    <ul>
        {% archiveList products with type="list" categoryId=item.Id limit="8" %}
            {% for inner in products %}
                <li><a href="{{inner.Link}}">{{inner.Title}}</a></li>
            {% endfor %}
        {% endarchiveList %}
    </ul>
{% endif %}

You can also use in conditional expressions,and/or/notUse logical operators to combine more complex conditions, such as:

{% if user.IsLoggedIn and user.IsVip %}
    <p>欢迎尊贵的VIP用户,这是专属内容!</p>
{% endif %}
{% if not archive.IsPublished %}
    <p>此文章仍在草稿状态,暂未发布。</p>
{% endif %}

Through these flexibleifStructure, you can precisely control the display and hide of page elements, so that your website content can present the most appropriate form according to different situations.

Powerful looping display:forThe art of looping tags.

forThe tag is a key tool in Anqi CMS templates used for traversing arrays, slices, or other iterable objects, allowing you to dynamically generate lists, navigation, image galleries, and other repetitive content without manually writing each element.

forThe basic structure of the loop is as follows:

{% for item in collection %}
    <!-- 针对集合中每个item显示的内容 -->
{% endfor %}

For example, to display a list of multiple articles under a category:

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {% for item in archives %}
        <li>
            <a href="{{item.Link}}">
                <h5>{{item.Title}}</h5>
                <p>{{item.Description}}</p>
            </a>
        </li>
    {% endfor %}
{% endarchiveList %}

It is worth mentioning,forThe loop also provided aemptyA clause used to display a backup content when the collection in the loop is empty, which is very helpful for improving user experience:

{% for item in archives %}
    <li><a href="{{item.Link}}">{{item.Title}}</a></li>
{% empty %}
    <li>当前分类下没有找到任何文章。</li>
{% endfor %}

ByemptyClauses, you can avoid the page from looking empty when there is no data and provide friendly prompts to users.

During the loop process, you can also access some special loop variables, such as:

  • forloop.Counter: The current iteration count, starting from 1.
  • forloop.Revcounter: The remaining iteration count, calculated in reverse.

These variables are very useful when you need to add style or numbering to specific items in a loop:

{% for item in archives %}
    <li class="{% if forloop.Counter == 1 %}first-item{% endif %}">
        <span>{{ forloop.Counter }}.</span> <a href="{{item.Link}}">{{item.Title}}</a>
    </li>
{% endfor %}

Furthermore,forLoops also supportreversedandsortedModifiers used for traversing in reverse order and traversing after sorting by default. Although they are not as commonly used as basic loops, they can provide more convenience in certain scenarios.

Integrated application:ifwithforCollaborative work

In actual template development,ifandforLabels are often used together. You might use one in aforuse labels insideifto display different content based on the different properties of each item, or in aifcondition that includes oneforLoop to display a list under specific conditions.

For example, in a navigation list, you may need to iterate through all navigation items and add different styles or display different structures based on whether a navigation item has a sub-navigation or is the current page:

{% navList navs %}
    <ul>
    {% for item in navs %}
        <li class="{% if item.IsCurrent %}active{% endif %}">
            <a href="{{ item.Link }}">{{item.Title}}</a>
            {% if item.NavList %} <!-- 如果有子导航 -->
            <dl>
                {% for subItem in item.NavList %}
                    <dd class="{% if subItem.IsCurrent %}active{% endif %}">
                        <a href="{{ subItem.Link }}">{{subItem.Title}}</a>
                    </dd>
                {% endfor %}
            </dl>
            {% endif %}
        </li>
    {% endfor %}
    </ul>
{% endnavList %}

When displaying rich text content retrieved from the background using these tags, be sure to use a|safefilter to prevent HTML tags from being escaped and displayed as plain text:

<!-- 如果 archiveContent 包含 HTML 标签,需要使用 |safe 过滤器 -->
<div>{{ archiveContent|safe }}</div>

by cleverly combiningifandforYou can build highly dynamic, responsive, and content-rich web page that meets various complex content display needs.These logical tags provided by AnQi CMS will greatly improve the efficiency and flexibility of your content operations.


Frequently Asked Questions (FAQ)

1. When I useforWhen iterating over a list, if the list is empty, nothing is displayed on the page. How can I display a 'No content' prompt?You can useforrepeatedlyemptyThe clause. When the loop collection is empty,emptythe content in the clause will be displayed. For example:

{% for item in articles %}
    <p>{{ item.Title }}</p>
{% empty %}
    <p>抱歉,目前没有找到任何文章。</p>
{% endfor %}

2. How toforAdd unique styles or behaviors to the first, last, or specific position elements in the loop?InforInside the loop, you can useforloop.Counterandforloop.RevcounterThese special variables.forloop.CounterRepresents the current loop number (starting from 1),forloop.RevcounterIndicates how many items are left to the end of the loop. For example, add to the first elementfirstClass: