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

Calendar 👁️ 57

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:

Related articles

How to truncate the title or abstract of an article and display it with an ellipsis?

In website content operation, titles and summaries are important elements to attract visitors to click and learn more details.Especially on list pages, recommendation positions, or the homepage, the limited space requires us to refine and cut these contents.To maintain the neatness and aesthetics of the page while fully conveying the core information, it is a common optimization strategy to truncate overly long article titles or summaries and end them with an ellipsis "..."}AnQiCMS (AnQi CMS) provided us with flexible and powerful tools to meet this requirement.

2025-11-07

How to display the custom parameter list in the article content on the front page?

AnQiCMS as an efficient and customizable content management system provides powerful content model features, allowing us to add various custom fields to articles according to different business needs.These custom parameters not only make the article content more rich and structured, but also allow for personalized display on the front page, greatly enhancing the flexibility and user experience of the website.Today, let's delve into how to flexibly display these custom parameter lists in the AnQiCMS front page.

2025-11-07

How to use the `pagination` tag to build standard pagination navigation in the template?

When the content of a website becomes richer, a clear and efficient pagination navigation system is crucial for improving user experience.The AnQiCMS template system provides a powerful `pagination` tag that allows us to easily build standard, beautiful pagination navigation.Next, we will delve deeper into how to use this tag in templates.

2025-11-07

How to display the number of comments for each article on the article list page?

In website operation, the article list page is not only the entrance of content, but also a window for users to understand the activity level of the website.When users see that every article is accompanied by a comment count, this not only effectively enhances the interactivity and attractiveness of the article, but also brings positive social proof to the website, encouraging more readers to participate in discussions.For users who use AnQiCMS, displaying the number of comments for each article on the article list page is a very direct and practical feature.

2025-11-07

How to safely display rich text content containing HTML tags on the front-end page?

In website operation, we often need to display rich content that includes images, links, bold text, and so on, which is known as rich text content.But it is a practical and careful task to safely display these rich text with HTML tags on the front-end page.AnQi CMS as an efficient content management system, fully considers this point, and provides us with a clear solution.

2025-11-07

How to dynamically display the current year or current time in a template?

In website operation, we often need to dynamically display the current year or time, such as displaying the latest copyright year at the bottom of the website, or marking the generation time of the page accurately in articles.AnqiCMS provides flexible and powerful template functions, making these operations very simple.Next, we will discuss how to implement this requirement in the AnqiCMS template.

2025-11-07

How to reflect the high concurrency characteristics of the Go language in the front-end page loading speed?

In today's fast-paced online world, website loading speed has become a core factor in user experience and search engine rankings.Nobody likes to wait for a slow page, and search engines tend to rank websites that respond quickly higher.How can you make your website lightning fast?For users of AnQiCMS, the answer is hidden in its powerful Go language underlying architecture, especially the high concurrency features that Go language boasts.

2025-11-07

How to reference and display external static resources (such as CSS, JS) in the template?

Referencing and displaying external static resources in AnQiCMS templates, such as CSS style sheets and JavaScript scripts, is a key step in building a functional and visually appealing website.Understand the working principle and recommended practices, which can make our website development work more efficient and flexible.

2025-11-07