How to use conditional judgment and loop structures to dynamically display content in AnQiCMS templates?

In AnQiCMS templates, dynamic content display is the core of building interactive and data-driven websites.By using conditional judgment and loop structures, you can flexibly present information based on different data states, or efficiently traverse datasets to generate lists, tables, and other content.AnQiCMS's template engine uses syntax similar to Django templates, making these operations intuitive and easy to learn.

Next, we will delve into how to effectively use these powerful tools in the AnQiCMS template.

1. Conditional judgment: flexible display of content

Conditional structures allow your template to decide whether to display certain content based on specific conditions, or which part of the content to display.This is very useful when handling different user states, the existence or absence of data, or specific page logic.

Passing the conditional judgment in AnQiCMS template{% if ... %}Implemented with tags. Its basic structure is similar to many programming languages, supportsif/elif(short for else if) andelseclauses.

Basic usage:{% if condition %}You can use it to check if a variable exists, is true, or meets certain conditions. For example, on the article detail page, we only display it if the article has a thumbnail:

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

Here, archive.ThumbIt will be evaluated as a boolean value, if there is a thumbnail path (non-empty string), the condition is true.

Operator in conditional judgment:You can combine multiple operators to build complex conditions:

  • Comparison operator:==(equals,)!=(not equal,)>(greater than,)<(less than,)>=(greater than or equal to,)<=(less than or equal to).
  • Logical operator:and(AND),or(OR),not(Not).
  • Member operator:in(Check if an element exists in a set).

For example, check if the article ID is 10:

{% if archive.Id == 10 %}
    <p>这是文档ID为10的文档。</p>
{% endif %}

Check if the current item in the loop is the first in the list:

{% if forloop.Counter == 1 %}
    <span class="first-item-badge">热门</span>
{% endif %}

Provide an alternative:{% if ... %}{% else %}When the condition is not met, you may need to display another segment of content. In this case, you can useelse:

{% if archive.Content %}
    <div class="article-content">{{ archive.Content|safe }}</div>
{% else %}
    <p>抱歉,该文章内容正在撰写中,请稍后再访问。</p>
{% endif %}

|safeThe filter is very important here, it tells the template engine not to escape HTML tags in the article content, thereby correctly rendering rich text.

Multiple condition judgment:{% if ... %}{% elif ... %}{% else %}If your logic needs to handle multiple cases, you can useelif:

{% if user.IsVip %}
    <p>欢迎VIP会员,您可查看所有内容。</p>
{% elif user.IsLoggedIn %}
    <p>欢迎普通会员,部分高级内容需要升级VIP。</p>
{% else %}
    <p>请登录以查看更多内容。</p>
{% endif %}

In the above example, we assume thatuserobjects and theirIsVipandIsLoggedInProperty.

II. Loop structure: bulk generation of content

The loop structure is the key to handling collection data (such as article lists, category lists, image lists).By using loops, you can avoid repeating similar code, making the template more concise and easier to maintain.

The loop structure in AnQiCMS template passes{% for ... in ... %}Tag implementation.

Basic usage:{% for item in collection %}Loop through a collection, and assign the current element toitemVariable.

For example, get the latest 10 articles and display their titles and links:

{% archiveList archives with type="list" limit="10" %}
    <ul>
        {% for article in archives %}
            <li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
        {% endfor %}
    </ul>
{% endarchiveList %}

HerearchiveListIt is an AnQiCMS built-in document list tag, which will store the query results toarchivesvariables, forforCyclic use.

Handle an empty collection:{% for ... %}{% empty %}If the collection in the loop may be empty, you can useemptya clause to provide a friendly prompt:

{% archiveList archives with type="list" categoryId="1" limit="5" %}
    {% for item in archives %}
        <div class="news-item">
            <h4><a href="{{ item.Link }}">{{ item.Title }}</a></h4>
            <p>{{ item.Description|truncatechars:100 }}</p> {# 使用truncatechars过滤器截断描述 #}
        </div>
    {% empty %}
        <p>当前分类下暂无文章。</p>
    {% endfor %}
{% endarchiveList %}

special variables in the loop:forloopInforInside the loop, the template engine provides a special variable namedforloopwhich contains information about the current loop state and is very useful:

  • forloop.Counter: The index of the current iteration starting from 1 (1, 2, 3…).
  • forloop.Revcounter: The index of the current iteration starting from the reverse of the total number of sets (…3, 2, 1).

These variables can be used to add numbers, apply special styles to the first or last element, etc.

For example, add background color to even rows:

{% categoryList categories with moduleId="1" parentId="0" %}
    {% for cat in categories %}
        <li class="{% if forloop.Counter is divisibleby:2 %}even-row{% else %}odd-row{% endif %}">
            <a href="{{ cat.Link }}">{{ cat.Title }}</a>
        </li>
    {% endfor %}
{% endcategoryList %}

Hereis divisibleby:2Is a filter used to determine if a number is divisible by 2.

Loop modifier:reversedandsortedYou canforAdd after tagreversedorsortedKeyword to change the order of the loop:

  • {% for item in collection reversed %}: Traverse the collection in reverse order.
  • {% for item in collection sorted %}:Follow the default order (usually by ID or name) and iterate.

Repetition pattern:{% cycle ... %}When you need to alternate between different values or CSS classes in a loop,cyclethe tag is very convenient:

{% archiveList archives with type="list" limit="5" %}
    {% for article in archives %}
        <li class="{% cycle 'list-item-odd' 'list-item-even' %}">
            <a href="{{ article.Link }}">{{ article.Title }}</a>
        </li>
    {% endfor %}
{% endarchiveList %}

This will make each article's<li>tags alternate owninglist-item-oddandlist-item-evenClass.

3. Combined use: Building complex pages

Conditional judgments and loop structures are often used together to deal with more complex page logic and data display requirements.

Example: Navigation with submenusA common scenario is to build a multi-level navigation menu. Submenus are displayed only when the main menu item has a submenu:

`twig\n{% navList navs %}

<ul class="main-menu">
    {% for item in navs %}
        <li class="main-menu-item {% if item.IsCurrent %}active{% endif %}">
            <a href="{{ item.Link }}">{{ item.Title }}</a>
            {% if item.NavList %} {# 检查是否存在下级导航 #}
                <ul class="sub-menu">
                    {% for subItem in item.NavList %}
                        <li class="sub-menu-item {% if subItem.IsCurrent %}active{% endif %}">
                            <a href="{{ sub