How to use if and for tags to implement conditional judgment and data display in templates?

When using AnQiCMS to build a website, the template is the key to displaying content.By flexibly using template tags, we can present the content of the back-end management in various forms to the users.ifandforThe tag is the core of template logic control, which can help us implement conditional judgment and cyclic display of data, making the website content more dynamic and rich.

AnQiCMS's template engine borrows the syntax style of Django, making the learning and use of these tags very intuitive.It allows us to write logic directly in the template, displaying different content based on different conditions, or iterating over a dataset to output each data item one by one, without complex programming knowledge.

I. Condition judgment: Flexible control of content display (ifLabel)

ifLabels are the basis for conditional judgment, allowing us to decide whether or not to display a piece of content and how to display it based on the truth or falsity of a certain condition. Its basic structure is very simple, through{% if 条件 %}and ends with{% endif %}End.

Basic Usage

Imagine that you want to display the article title on the article detail page, but some articles may be empty due to some reasons. You can useiftags to judge:

{% if archive.Title %}
    <h1>{{ archive.Title }}</h1>
{% else %}
    <h1>[无标题]</h1>
{% endif %}

This code will checkarchive.TitleDoes it exist, if it exists, then display the article title, otherwise display '[No Title]'.

Multiple conditions and else

When you need to handle more complex logic,ifTags also supportelif(else if) andelseTo construct multiple judgments. For example, you want to display different styles based on the article ID:

{% if archive.Id == 1 %}
    <p class="highlight-article">这是ID为1的特别文章。</p>
{% elif archive.Id > 100 %}
    <p class="new-article">这是一篇较新的文章,ID大于100。</p>
{% else %}
    <p>这是一篇普通文章。</p>
{% endif %}

Here, the template will first check if the article ID is 1, if not, then check if it is greater than 100, and finally if neither condition is met, display the prompt for a regular article.

Examples of practical scenarios

ifTags are widely used in practical applications. For example, determining whether a data set contains a thumbnail image to decide whether to display the image:

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

or in the navigation menu, add different CSS classes based on whether the current page is active:

<li class="{% if item.IsCurrent %}active{% endif %}">
    <a href="{{ item.Link }}">{{ item.Title }}</a>
</li>

These all demonstrate:ifthe powerful role of tags in controlling the visibility and style of page elements.

II. Loop Display: Efficiently Present List Data (forLabel)

forLabels are used to iterate over array or collection types of data, displaying each item in the collection one by one.This is crucial in scenarios such as displaying article lists, product lists, navigation menus, etc.{% for 变量名 in 集合 %}and ends with{% endfor %}End.

Basic Usage

Assuming you have obtained an article list from the AnQiCMS backend ({% archiveList archives with type="list" limit="10" %}This label acquisition) and assign it toarchivesThis variable. You can display it in a loop like this:

{% for article in archives %}
    <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 %}

Here,articleIt is each item in the loop, and we can access its properties througharticle.Title/article.Linketc.stampToDateis the date formatting function provided by AnQiCMS, which can convert timestamps into readable date formats.

Loop auxiliary variable

forThe loop also provides some very useful auxiliary variables, which help us better control the loop logic or display information:

  • forloop.Counter: The current iteration number of the loop, starting from 1.
  • forloop.Revcounter: The number of remaining loops until the end, counted from the total in reverse.

For example, if you want to add a 'new' tag to the first article in the list:

{% for article in archives %}
    <div class="article-item {% if forloop.Counter == 1 %}latest-article{% endif %}">
        {% if forloop.Counter == 1 %}<span>[最新]</span>{% endif %}
        <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
        <p>这是第 {{ forloop.Counter }} 篇文章。</p>
    </div>
{% endfor %}

Handle empty data

If the collection in the loop may be empty, you want to display a friendly prompt message when there is no data instead of leaving it blank, you can use{% empty %}Sub-tag:

{% for article in archives %}
    <!-- 显示文章内容 -->
{% empty %}
    <p>抱歉,目前没有可显示的文章。</p>
{% endfor %}

WhenarchivesThe collection is empty,{% empty %}the content within the block will be displayed.

Advanced Usage: Sorting and Reversing

forTags also supportreversedandsortedModifiers used to reverse or sort the collection before the loop (for integer arrays).

{% for item in archives reversed %}
    <!-- 以相反的顺序显示文章 -->
{% endfor %}

{% for item in some_numbers sorted %}
    <!-- 对数字进行排序后显示 -->
{% endfor %}

III.ifWithforThe combination of applications

ifandforThe true power of tags lies in their ability to create highly dynamic and interactive template structures when used together.

Build multi-level navigation menus

An example is to build a multi-level navigation menu. AnQiCMS'snavListTags can retrieve navigation data, which may contain sub-navigationNavList. We can utilizeforEnglish loop through the main navigation, and thenifDetermine if there is a sub-navigation, if there is, use it againforEnglish loop through the sub-navigation.

{% navList navs %}
<ul class="main-nav">
    {% for main_item in navs %}
        <li {% if main_item.IsCurrent %}class="active"{% endif %}>
            <a href="{{ main_item.Link }}">{{ main_item.Title }}</a>
            {% if main_item.NavList %} {# 判断是否有子导航 #}
                <ul class="sub-nav">
                    {% for sub_item in main_item.NavList %} {# 遍历子导航 #}
                        <li {% if sub_item.IsCurrent %}class="active"{% endif %}>
                            <a href="{{ sub_item.Link }}">{{ sub_item.Title }}</a>
                        </li>
                    {% endfor %}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
</ul>
{% endnavList %}

This example perfectly demonstratesifandforHow to collaborate, dynamically generate complex user interfaces based on the hierarchical structure of the data.

IV. Notes on writing templates

When usingifandforWhen labeling, there are some details to pay attention to in order to ensure the correctness and fluency of the template:

  • Label closure:. ifLabels must start with `{%