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

Calendar 👁️ 60

In the Anqi CMS template world,ifandforTags are the foundation for building dynamic and flexible web pages. They give templates the ability to display content based on different data conditions and efficiently loop through datasets, making your website content vividly presented to visitors.The AnQi CMS adopts a template engine syntax similar to Django, which makes it easy for you, who is familiar with web development, to get started, through double curly braces{{变量}}Get data, while conditional judgment and loop control are used{% 标签 %}Syntax.

UseifTags implement conditional display of dynamic content

ifThe core function of the tag is to decide whether to display a certain part of the page content based on specific conditions. Its syntax structure is very intuitive, supporting single condition judgment and multi-branch conditions, such as: {% if 条件 %} ... {% elif 其他条件 %} ... {% else %} ... {% endif %}

In practical applications,ifThe label's 'condition' can be very diverse. You can perform boolean judgments, such as checking if a switch is turned on to display or hide a specific function module.Data variable non-empty checks are also very common, such as{% if archive.Thumb %}Can determine whether the current document has a thumbnail, if it does, it should be displayed, if not, consider displaying a default placeholder to avoid blank areas on the page that are missing content.

Comparison operator (==/!=/</>/<=/>=)You can control the display based on the comparison result of numbers or strings. For example,{% if archive.Id == 10 %}You can display unique information for a specific document with ID 10 in the template. In addition,inandnot inThe operator is used to check if a value exists in a set (such as an array or string), which is very useful for content filtering based on user permissions or article tags.

Skillfully useifLabels can help you achieve many functions: for example, displaying personalized welcome messages for logged-in users, or based on the 'recommended' attribute of articles (such asarchive.Flag == "h"This represents the headline and adds a prominent mark. This conditional display mechanism is the key to creating a personalized, interactive website experience.

UtilizeforTags implement the cyclic display of content.

When you need to display a series of similar contents,fortags come into play. It can iterate over each item in a collection and present each one according to the template definition. Its basic syntax is:{% for item in collection %} ... {% endfor %}

In each iteration,itemthe variable will represent the current element of the collection, and you can access its properties by{{item.Title}}/{{item.Link}}and so on. Anqi CMS'sforLoops also provide several very useful built-in variables:

  • forloop.CounterThis indicates the current loop count, starting from 1. This is especially convenient when adding special styles or numbering to the first item in a list.
  • forloop.Revcounter: Indicates the number of iterations remaining after the loop ends.

A noteworthy feature is thatemptyclause. When the collection you are looping through is empty,emptyThe content under the clause will be executed, which is more concise and elegant than using it traditionally first.ifIt is more concise and elegant to loop over the empty set before the judgment.{% for item in archives %} ... {% empty %} <div>暂无相关内容。</div> {% endfor %}

forTags play an important role in building website parts: it can traverse and display article lists, product lists, navigation menus, friend links, and even image groups in custom fields. ThroughreversedModifiers can enable reverse traversal,sortedModifiers can sort the collection according to specific rules, meeting more diverse display needs.

ifwithforcollaborative application: building complex dynamic pages

In actual template development,ifandforLabels are often combined to achieve more complex logic and richer dynamic effects.

For example, in the loop of the article list, you may want to add a special "latest" tag or a unique style to the first article. At this point, you can combineforloop.CounterandifTag implementation:{% for item in archives %} <li{% if forloop.Counter == 1 %} class="first-article"{% endif %}> <a href="{{ item.Link }}">{{ item.Title }}</a> </li> {% endfor %}

Or perhaps, when building a multi-level category navigation, you may need to determine whether the current category has subcategories: if it does, then display the subcategory list; if not, then display the article list under the category. In this case,ifandforNested use is indispensable:{% categoryList categories with parentId="0" %} {% for category in categories %} <div> <h3>{{ category.Title }}</h3> {% if category.HasChildren %} {% categoryList subCategories with parentId=category.Id %} <ul>{% for subCategory in subCategories %}<li><a href="{{ subCategory.Link }}">{{ subCategory.Title }}</a></li>{% endfor %}</ul> {% endcategoryList %} {% else %} {% archiveList articles with categoryId=category.Id limit="5" %} <ul>{% for article in articles %}<li><a href="{{ article.Link }}">{{ article.Title }}</a></li>{% endfor %}</ul> {% endarchiveList %} {% endif %} </div> {% endfor %} {% endcategoryList %}

Moreover, in order to make the template code cleaner, Anqin CMS also supports using hyphens at the beginning or end of tagsifandforUsing hyphens at the beginning or end of tags-Remove the whitespace taken up by logical tags. For example,{%- if condition %}or{% endfor -%}This is very useful when generating HTML structures that do not require additional whitespace.

By flexible applicationifandforThese powerful template tags allow you to organize data effectively, make conditional judgments based on business logic, and present it dynamically and expressively on the front end of the website, thereby building a functional and user-friendly Anqi CMS website.

Frequently Asked Questions (FAQ)

  1. How to add special styles or content to items that meet specific conditions in a loop (such as the first, last, or even-numbered items)?You can useforloop.Counterandforloop.RevcounterThese built-in variables work togetherifTo implement a tag. For example,{% if forloop.Counter == 1 %}It can be determined whether it is the first item,{% if forloop.Last %}Or if supported{% if forloop.Revcounter == 1 %}It can be determined whether it is the last item. For even or odd items, it can be determined through{% if forloop.Counter % 2 == 0 %}to judge.

  2. When passedforHow to avoid the page displaying blank when the label traversal list may be empty, but instead give the user a friendly prompt?In this case,forlabel'semptyThe clause is an ideal solution. WhenforWhen the data collection has no content,{% empty %}and{% endfor %}the content between them will be executed. For example:{% for item in articles %} ... {% empty %} <div>抱歉,暂时没有找到任何文章。</div> {% endfor %}.

  3. ifWhat types of conditional judgments can the tag make? Besides simple true or false, what else can I do? ifTags support various powerful conditional judgments. You can make precise numerical or string comparisons(==/!=), size comparisons(>/</>=/<=),as well as checking if a variable exists or is not empty. Moreover, you can useinandnot into determine if a value is contained within a collection (such as an array or a string). Complex logic can be achieved byandandorConnect multiple conditions.

Related articles

How to generate and control the pagination display effect of the `pagination` tag?

In website operation, when the amount of content is large, how to efficiently and beautifully display these contents while ensuring that users can browse conveniently is the key to improving user experience.If you dump all the content on the same page, not only will it load slowly, but it will also deter visitors.At this moment, content pagination becomes particularly important. It breaks massive information into several pieces, which not only reduces the burden of page loading but also allows users to explore the content they are interested in step by step at their own pace.AnQiCMS provides a powerful and flexible `pagination` tag

2025-11-08

How to implement content aggregation and thematic display based on `tagList` and `tagDetail` tags?

In content management and website operations, how to efficiently organize and display content is the key to improving user experience and SEO performance.AnQiCMS provides powerful tag features, with the `tagList` and `tagDetail` template tags, it is easy to implement content aggregation based on tags and thematic display, bringing more flexible classification and richer navigation experience to the website.### The role of tags in content aggregation Tags are an important way to organize content in a content management system

2025-11-08

How to manage and display independent single-page content for the `pageList` and `pageDetail` tags?

In website operation, in addition to dynamically updated articles or product lists, we often need to display some relatively fixed and independent content pages, such as "About Us", "Contact Information", "Privacy Policy" or "Service Introduction" and so on.These pages are usually called "single-page content". AnQiCMS provides us with powerful and flexible tools for managing and displaying these pages, especially the core tags `pageList` and `pageDetail`.### Single Page Content: The Foundation of a Website Single page content is an indispensable part of a website

2025-11-08

How are the `categoryList` and `categoryDetail` tags used to build and display the hierarchical structure of the website?

In Anqi CMS, the classification hierarchy of the website is the core of content organization, which not only affects the user's browsing experience, but is also an important link in search engine optimization.To effectively build and display these classification structures, we mainly rely on two powerful template tags: `categoryList` and `categoryDetail`.They work together, allowing you to flexibly present clear and organized content categories on the website front-end.### Build the category list: `categoryList` tag `categoryList`

2025-11-08

How to format a timestamp with the `stampToDate` tag to display the date and time in a user-friendly manner?

In the daily content operation of Anqi CMS, we often need to present the original timestamp data such as publish time and update time in a way that is more accustomed to and easier to read for users.The original timestamp, such as `1609470335` such a pure number sequence, has no meaning to ordinary users.To solve this problem, AnQi CMS provides a very practical template tag——`stampToDate`, which can help us convert these numeric timestamps into a clear and user-friendly date and time display.###

2025-11-08

How to retrieve and display the global configuration and SEO information of the website using `system`, `contact`, and `tdk` tags?

In the daily operation of AnQiCMS (AnQiCMS), accurately displaying global configuration information, contact information, and carefully optimized SEO elements on the website front end is the key to improving user experience and search engine visibility.Fortunately, AnQiCMS provides several intuitive and powerful template tags that allow users to easily access this important data.This article will delve into the three core tags `system`, `contact`, and `tdk`, helping you seamlessly integrate the background configuration into various pages of the website.Get the global configuration of the website

2025-11-08

How to build and display the navigation path of the current page in the website using the `breadcrumb` tag?

In website construction and operation, user experience (UX) is always at the core.When visitors delve deeper into your website, a clear navigation path can effectively prevent them from getting lost and quickly understand their current location.This is the value of the 'Breadcrumb Navigation'.It not only enhances user experience, but is also an important part of Search Engine Optimization (SEO), helping search engines understand the hierarchy of your website structure.AnQi CMS knows this and therefore provides a convenient and easy-to-use `breadcrumb` tag

2025-11-08

How does AnQiCMS support Markdown content editing and correctly render mathematical formulas and flowcharts on the front end?

AnQiCMS understands the desire of content creators for efficient and flexible editing tools.The new version introduces Markdown editor, greatly enhancing the convenience of content publishing.It is even more surprising that AnQiCMS not only supports basic Markdown syntax but also allows complex mathematical formulas and flowcharts to be elegantly presented on your website front-end through simple configuration.This is undoubtedly a powerful boost for websites that need to display professional knowledge, technical documentation, or educational content.### Enable Markdown Editing Feature First

2025-11-08