How to conditionally display different content or styles within a loop?

Calendar 👁️ 64

In website content display, we often encounter such needs: to display different content or assign unique styles to elements based on the order of data cycles, specific attributes, or states.For example, the odd and even rows of the list need different background colors, specific types of products need special marking, or the corresponding area should be hidden when a field is empty.

AnQi CMS with its flexible and powerful Django-like template engine makes these requirements simple and easy to implement. By cleverly combining loop tags ({% for ... %})and conditional judgment tags({% if ... %}series), you will be able to have precise control over the display of website content.

Core feature analysis: the foundation of loops and conditional judgment.

First, let's review the two core tools for implementing conditional display and style customization:

1. Loop tags ({% for ... %})This is the foundation for you to traverse the dataset. Whether it is an article list, product classification, or navigation menu,fortags can help you access each element in the collection one by one. For example, you can access{% archiveList archives with type="page" limit="10" %}Retrieve the list of articles and then{% for item in archives %}traverse these articles.

Inside the loop,itemThe variable represents the current data object being iterated over, which includes the title (item.Title), link (item.Link) and various properties.

2. Conditional judgment tag ({% if ... %}SeriesThis is the key to implementing 'conditionality'. Anqi CMS provides{% if 条件 %}/{% elif 其他条件 %}(short for else if) and{% else %}Labels, allowing you to decide which content will be rendered and which styles will be applied. For example,{% if item.Thumb %}It can determine whether the current article has a thumbnail.

3. Loop built-in variables (forloop.Counterwithforloop.Revcounter)InforIn the loop, you can also access some special built-in variables that provide information about the current loop state, which is particularly useful for customizing styles:

  • forloop.Counter: The current loop iteration number, starting from 1.
  • forloop.Revcounter: The remaining number of elements in the current loop.
  • forloop.First: If the current is the first element of the loop, then it is True.
  • forloop.Last: If the current is the last element of the loop, then it is True.

Having mastered these basic tools, we can start building various practical conditional display scenarios.

Practice Exercise: Flexible Use of Conditional Display

Here are some common scenarios and their implementation methods:

Scenario one: Set different styles for odd/even rows

To make the data list more readable, we often need to apply different background colors or borders to odd and even rows.

Implementation method:Utilizeforloop.CounteranddivisiblebyFilter (used to determine if it can be divided evenly).

{% for item in archives %}
    <div class="list-item {% if forloop.Counter|divisibleby:2 %}even-row{% else %}odd-row{% endif %}">
        <h3>{{ item.Title }}</h3>
        <p>{{ item.Description }}</p>
    </div>
{% endfor %}

here,forloop.Counter|divisibleby:2It will check if the current line number is even. If it is even, then applyeven-rowclass; otherwise applyodd-rowClass.

Scenario two: highlight the first and last elements of the list

Sometimes, you may need to add special visual effects to the first or last element of a list, such as 'latest' or 'recommended' tags.

Implementation method:Utilizeforloop.Firstandforloop.Last.

{% for item in archives %}
    <div class="list-item {% if forloop.First %}first-highlight{% elif forloop.Last %}last-special{% endif %}">
        {% if forloop.First %}
            <span class="badge new-badge">最新</span>
        {% endif %}
        <h3>{{ item.Title }}</h3>
        <p>{{ item.Description }}</p>
    </div>
{% endfor %}

This code will add to the first element of the listfirst-highlightAnd the “Latest” badge; add to the last elementlast-specialClass.

Scenario three: Display different content or style based on specific data values

If you want to display or hide content based on the article ID, category name, or a specific field value, or change the style, this is the most commonly used conditional judgment.

Implementation method:Directly compare the attribute values of data objects.

`twig {% for item in archives %}

<div class="list-item">
    {% if item.

Related articles

How to display the names and introduction information of different user groups?

Displaying different user group names and introduction information in AnQi CMS is an important part of website personalized operation and content distribution.Whether you want to display exclusive identification for VIP members or provide customized content for users with different permissions, Anqi CMS's flexible template tag system can help you easily achieve this. ### Understanding the Core Concepts of User Group Information To display the name and introduction of the user group, it is first necessary to clarify two key points: whether the user is logged in, and which user group the user belongs to. Safe CMS provides powerful template tags

2025-11-08

How to display detailed information of the currently logged-in user (such as username, avatar, VIP status)?

In Anqi CMS, displaying the detailed information of the currently logged-in user, such as username, avatar, and VIP status, is a key step to enhance user experience and build a personalized website.AnQi CMS with its flexible template engine allows us to easily implement these features.This article will introduce how to display this information on your website front-end. ## Retrieve basic information of the currently logged-in user The Anqi CMS template system provides the `userDetail` tag, which is the core tool for retrieving various information of the currently logged-in user.This tag can directly retrieve the user data of the current session

2025-11-08

How to configure and display thumbnails with different processing methods (such as cropping, scaling)?

##驾驭安企CMS缩略图:精细化的配置与灵活的展示,打造视觉冲击力 在网站运营中,图片无疑是吸引用户、提升内容质量的关键元素。While thumbnails, as the first visual touchpoint of website content, their display effect directly affects users' desire to click and the overall beauty of the page.AnQi CMS knows this and provides us with flexible thumbnail configuration and display capabilities, helping us easily manage and present high-quality image content.### Core Configuration

2025-11-08

How to automatically compress images based on size and display them on the front-end?

In website operation, images are an important element to attract visitors and convey information.However, large, unoptimized images often become the 'killer' of website loading speed, not only affecting user experience, but also possibly dragging down search engine rankings.Luckyly, AnQiCMS (AnQiCMS) provides very intelligent and practical image processing functions that can help us easily cope with these challenges, making images clear and fast when displayed on the front end.### Smart compression, goodbye to manual adjustment of large images Have you ever encountered such a situation: in order to maintain image quality

2025-11-08

How to define and display temporary variables in the template?

In Anqi CMS template development, mastering how to define and display temporary variables in the template is a very practical skill.It can help us handle data more flexibly, optimize template structures, and write more concise and efficient code.Temporary variables are like the "small tags" you grab on the fly while making a page, used to temporarily store some data for later use.### Why do we need temporary variables? Imagine a scenario: you might need to get a value from a label and then perform a series of operations on it (such as truncating strings, formatting time)

2025-11-08

How to reference and display common code snippets (such as header, footer) in AnQiCMS templates?

It is crucial to maintain consistency in page structure and code maintainability in website construction and content management.For a content management system like AnQiCMS, effectively referencing and managing common code snippets, such as the website header (Header) and footer (Footer), is the key to achieving this goal.Through AnQiCMS's flexible template mechanism, even users with little understanding of technical details can easily implement these features, thus building a website with clear structure and easy maintenance.###

2025-11-08

How to use the template inheritance mechanism to unify and display the website page structure?

When building a website, maintaining consistent page structure, improving development efficiency, and reducing maintenance costs are key to website operations.AnQiCMS (AnQiCMS) leverages its powerful functionality based on the Django template engine syntax to provide us with an efficient template inheritance mechanism, making it easy to unify and flexibly display the structure of web pages. ### The core concept of template inheritance: building the skeleton of a website Imagine that your website is like a house made up of different rooms. Each room (page) has its unique functions and content, but they share the same foundation

2025-11-08

How to dynamically display the current year or a specified date on a website?

In website operation, we often need to display some dynamic time information, such as the copyright year at the bottom of the website (such as “© 2023-Current Year”), the publication or update time of articles, or the deadline for specific events, etc.These dynamic dates not only maintain the timeliness of website information, but also improve user experience, and in some cases, are also beneficial for SEO. The AnQi CMS provides a series of flexible template tags that allow you to easily display the current year or a specified date dynamically at any location on the website.We will discuss in detail how to make use of these features.

2025-11-08