How `if` logical judgment tags and `for` loop iteration tags control the conditional display and repeated display of content?

Calendar 👁️ 75

In the daily operation of AnQi CMS, we often need to decide according to different business logic which content should be displayed, and how to efficiently repeat the display of a large number of similar contents. At this time,ifLogical judgment tags andforThe loop to traverse tags becomes an indispensable tool in template design.They allow us to flexibly control the conditional display and repetition of content, greatly enhancing the dynamism and maintainability of the website.

Conditional display tool -iflogical judgment tag

ifTags are the basis for conditional display of content in Anqi CMS templates.It allows us to set one or more conditions, and the corresponding template content will be rendered only when these conditions are met.This is very useful in many scenarios, such as displaying specific information based on the user's permissions, or determining whether to display certain data based on its existence.

The basic usage is to determine whether a variable exists or is true.For example, on the article detail page, we may want to display the image only when the article is set with a thumbnail, otherwise it should not be displayed to avoid broken image placeholders.This is how it can be written:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}" class="article-thumb">
{% endif %}

here,archive.ThumbRepresents the thumbnail path of the article. If this path exists (not empty), thenifThe condition is met, and the image will be displayed.

When the logical judgment needs to be more complex,ifTags also supportelif(short for else if) andelseto handle multiple branching conditions. For example, we want to display different badges based on the recommendation attributes of the article(Flag):

{% if archive.Flag == "h" %}
    <span class="flag-hot">头条</span>
{% elif archive.Flag == "c" %}
    <span class="flag-recommend">推荐</span>
{% else %}
    <span class="flag-normal">普通</span>
{% endif %}

Through such a structure, we can easily deal with various combinations of conditions, ensuring that the content is presented according to precise business rules. At the same time,ifthe label also supports various comparison operators (such as==/!=/</>/>=/<=)and logical operators(and/or/not)even can pass throughinto determine whether a value is included in a set, making conditional judgment more powerful and flexible.

Master of repetitive content layout——forLoop through tags

On the website, article lists, product displays, navigation menus, image galleries, and other content often have repetitive structures.forThe loop iteration tag is born to solve such problems, it allows us to efficiently traverse a data collection (such as an array, slice, or map), and render the same template structure for each element of the collection, but fill in different data.

A common scenario is to display the latest article list. ByarchiveListtags to get the collection of articles, we can thenforuse a loop to sequentially display the title and link of each article:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <li class="article-item">
            <a href="{{ item.Link }}">{{ item.Title }}</a>
            <p>{{ item.Description|truncatechars:100 }}</p>
        </li>
    {% endfor %}
{% endarchiveList %}

here,archivesIsarchiveListThe tag returns a collection of article list data,itemwhich represents the current article object in the loop. Each loop,itemWill automatically update to the next article data in the list until all articles are processed.

Furthermore,forThe loop also provides some useful auxiliary variables and functions. For example,forloop.CounterYou can get the current loop index (starting from 1),forloop.RevcounterThis indicates the remaining number of loop iterations. These are very useful when you need to add special styles to the first or last element of a list:

{% for item in archives %}
    <li class="article-item {% if forloop.Counter == 1 %}first-item{% endif %}">
        <!-- 内容 -->
    </li>
{% endfor %}

Furthermore,forTags also supportreversedto traverse the set in reverse order,sortedSort the set of numbers as wellcycleTag to alternate the predefined string sequence in a loop (for example, to alternate the setting of list items)oddandevenClass name), these can make our template design more exquisite.

If you encounter an empty data set,forthe loop also providesemptyblocks to elegantly handle. Whenarchivesthe list is empty,emptyThe content within the block will be rendered, preventing the page from appearing blank or with errors:

{% for item in archives %}
    <!-- 文章列表内容 -->
{% empty %}
    <p class="no-content">当前暂无文章。</p>
{% endfor %}

Optimize the experience: Details in control and skills

In practical applications,ifandforLabels are often used together to achieve finer content control. For example, when displaying a list of categories in a loop, we may want only items with subcategories to expand and display their subcategories:

{% navList navList %}
    {% for item in navList %}
        <li>
            <a href="{{ item.Link }}">{{ item.Title }}</a>
            {% if item.NavList %} {# 判断是否有下级导航 #}
                <ul class="sub-menu">
                    {% for subItem in item.NavList %}
                        <li><a href="{{ subItem.Link }}">{{ subItem.Title }}</a></li>
                    {% endfor %}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
{% endnavList %}

Here, outer layerforLoop through the main navigation items, inner layerifConditionally judge whether each main navigation item hasNavList(sub-navigation list). If there is, then go through another inner layer}forLoop through and display sub-navigation items.

Another practical trick is to use the template tag's blank line removal feature. Iniforforadd before and after the tag.-The symbol, can remove the blank line occupied by the tag, which is very useful for generating compact HTML code, especially when dealing with list items or inline elements:

{%- for item in archives %}
    {{- item.Id }}
{%- endfor %}

This ensures that the generated HTML does not contain any unnecessary blank lines, making the code cleaner.

By mastering the use ofifandforThese two core tags, combined with the rich data tags provided by Anqi CMS, allow us to flexibly build various complex and dynamic website content layouts like building blocks.This not only improves the development efficiency, but also provides great convenience for the long-term operation and content update of the website.


Frequently Asked Questions (FAQ)

  1. Question:ifTags can be used to determine what types of data?Answer:ifTags are very flexible, can judge boolean values (trueorfalse), numeric size, whether the string content matches, whether the variable exists (non-empty), and even throughinThe operator determines whether a value is contained within an array or a map. This makes it capable of covering the vast majority of conditional judgment needs.

  2. Question: How toforApply different styles to list items in a loop, such as alternating colors?Answer: You canforUsing a loopcycletags. For example, `{% cycle "odd" "even"}

Related articles

How does the pagination tag `pagination` provide navigation and display control for long content lists?

In website operation, when our content list (whether it is articles, products, or other information) accumulates to a certain amount, displaying all content on a single page not only significantly affects the page loading speed but may also make visitors feel overloaded with information, making it difficult for them to find the content they are really interested in.At this point, a reasonable pagination mechanism is particularly important. AnQiCMS provides a powerful and flexible `pagination` tag, which helps us provide clear navigation and display control for long content lists, thereby greatly optimizing user experience and website performance.Core Function

2025-11-07

How to display the link list of cooperative website links with the tag `linkList`?

In website operation, friendship links (also known as cooperative website links) play an important role.They not only bring additional traffic to the website, but also help to improve search engine optimization (SEO) performance, enhance the authority and user trust of the website.In Anqi CMS, managing and displaying these links becomes very convenient, mainly due to its powerful template tag system, especially the `linkList` tag.### Flexibly display cooperative websites: `linkList` tag usage and basic principles `linkList`

2025-11-07

How to dynamically generate and display the user's guestbook form with the label `guestbook`?

In website operation, visitor comments and interaction are important for building trust, obtaining feedback, and promoting business development.AnQiCMS (AnQiCMS) understands this need and provides a flexible and powerful message form feature, allowing you to easily generate and display user message forms on your website.This is mainly achieved through its built-in `guestbook` template tag, which not only allows you to customize form fields but also ensures the safety and smooth submission of the form.### Understand `guestbook`

2025-11-07

How to get and display the comments made by users on the content for the comment list label `commentList`?

In today's digital world, websites are not just platforms for displaying information, but also spaces for user interaction and communication.When users can express their opinions and ask questions about the content, the vitality of the website will be greatly enhanced.Anqi CMS knows this and therefore provides a powerful and flexible comment management feature, where the 'comment list tag `commentList`' is the key bridge connecting content and user feedback. Imagine that you have published an engaging article or an innovative product, and users can't wait to share their thoughts after reading it.As a website operator

2025-11-07

How to format the timestamp label `stampToDate` to display time data in a readable format?

In a content management system, time data often exists in the form of a series of numbers, which we call a Unix timestamp.This form is very efficient for machine processing, but for us users, a string like `1678886400` is obviously not intuitive to understand the date and time it represents.AnQi CMS knows this point well, therefore it provides a very practical template tag `stampToDate`, which helps us convert these cryptic timestamps into the date and time format we are accustomed to reading.###

2025-11-07

How `include`, `extends`, and `macro` auxiliary tags optimize the template structure and affect the final display of content?

In website operation, template design is a key link in building user experience and content presentation efficiency.AnQiCMS (AnQiCMS) provides strong support for content management with its flexible template engine.Especially among the auxiliary tags such as `include`, `extends`, and `macro`, they do not directly modify the content itself, but through optimizing the template structure, they profoundly affect the final display effect and maintenance efficiency of the website content.

2025-11-07

How to correctly display Markdown formatted mathematical formulas and flowcharts in AnQiCMS content?

For many content creators, especially when it comes to technical articles, tutorials, or data reports, it has always been a challenge to clearly and accurately display mathematical formulas and complex flowcharts on web pages.The traditional HTML editing method is not only繁琐but also prone to errors.It is fortunate that the new version of AnQiCMS has introduced support for Markdown editors, which brings great convenience to handling such complex content.It makes the creation of technical content more efficient and elegant.

2025-11-07

How do variables such as `{id}`, `{filename}`, `{catname}`, `{module}` and others affect the display structure of the URL in static rules?

When operating a website, we often pay attention to the quality of the content and the performance of the website, but there is a detail that is often overlooked but is crucial, that is, the structure of the URL (Uniform Resource Locator).A clear and meaningful URL can not only enhance the user experience, but is also an indispensable part of search engine optimization (SEO).Our company, Anqi CMS, understands this well and provides flexible and powerful pseudo-static functions, allowing us to customize URLs that are both aesthetically pleasing and SEO-friendly according to our needs.

2025-11-07