How to implement the `cycle` tag to alternate the display of different styles or data in AnQiCMS templates?

Calendar 👁️ 80

AnQiCMS provides many practical tags for template development, making content display more flexible and efficient. Among them,cycleTags are such a clever tool that they can help us achieve alternating display of data or styles in loops, making the page content more dynamic and visually attractive.

Get to knowcycleLabel: Sequence controller in loop

In web design, we often encounter situations where we need to apply different styles to repeated elements or display different types of data in a specific order.For example, the odd and even rows in the list need different background colors, or a set of product displays needs to alternate between the labels "New Arrivals" and "Best Sellers."}If only rely onforThe counter in the loop performs complexif/elseJudgment, the code will become long and difficult to maintain.

cycleTags were born, providing a concise and elegant way to solve such problems. Its core function is: inforIn each iteration, it outputs the parameters it carries in the preset order one by one. After all the parameters have been output once, it will automatically loop back to the first parameter and repeat.This is like an automatic switching sequence, making your content 'move' in a loop.

Why choosecycleTag?

UsecycleThe benefits of tags are self-evident. First, they greatly simplify template code. You can use a simple line ofcycleLabeling multi-line conditional judgments makes the template more readable and easier to manage.Secondly, it enhances the visual presentation of website content. By alternating styles, such as the background color of list items, it helps users better distinguish and read the content, improving the user experience.At the same time, for displaying different types of data,cycleIt can also make information presentation more hierarchical.

cycleBasic usage of tags: alternating styles

The most common use is to implement alternating row styles. Suppose we have a list of articles, and we want the background color of the list to alternate light and dark to increase visual contrast.

We can use it like thiscycleTags:

<ul class="article-list">
{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li class="{% cycle 'bg-light' 'bg-dark' %}">
        <h3 class="article-title"><a href="{{item.Link}}">{{item.Title}}</a></h3>
        <p class="article-description">{{item.Description}}</p>
    </li>
    {% empty %}
    <li>暂无文章内容。</li>
    {% endfor %}
{% endarchiveList %}
</ul>

In this example, we usearchiveListLabel to retrieve a list of articles andforiterate each article in the loop.{% cycle 'bg-light' 'bg-dark' %}It will be in each<li>Label rendering time, alternate'bg-light'and'bg-dark'These two strings asclassthe value of the attribute.

The specific effect will be like this:

  • The first article's<li>Tag acquiredclass="bg-light"
  • The second article's<li>Tag acquiredclass="bg-dark"
  • The third article's<li>The tag is obtained againclass="bg-light"
  • Continue in this way until the loop ends

In this way, without complex logical judgment, we easily achieved the alternating background color effect of the list rows

cycleAdvanced application of tags: alternating data or content

cycleTags can not only be used for style class names, but can also be used to alternate any text or data content.

For example, we may need to alternate different prompt texts in a list:

<div class="product-showcase">
{% archiveList products with moduleId="2" type="list" limit="6" %}
    {% for product in products %}
    <div class="product-card">
        <img src="{{product.Logo}}" alt="{{product.Title}}">
        <h4 class="product-name">{{product.Title}}</h4>
        <span class="product-tip">{% cycle '新品上架' '热销爆款' '限时优惠' %}</span>
    </div>
    {% empty %}
    <p>暂无产品信息。</p>
    {% endfor %}
{% endarchiveList %}
</div>

Here, {% cycle '新品上架' '热销爆款' '限时优惠' %}The three different prompt information will be displayed in a loop on the product card, assigning a dynamic attribute to each product, making the display more rich.

UsecycleLabel alias: improve code readability and reusability

When you need to use the same value multiple times in the same loop iterationcycleUse an alias when the label generates the same value (as alias) Functions will be very convenient. It can avoid repeated callscycleTags, improve the clarity and execution efficiency of the code

<div class="blog-posts">
{% archiveList posts with type="list" limit="4" %}
    {% for post in posts %}
    {% cycle 'primary' 'secondary' as card_theme %}
    <div class="post-card card-{{ card_theme }}">
        <h4 class="post-title"><a href="{{post.Link}}">{{post.Title}}</a></h4>
        <p class="post-meta">主题: {{ card_theme | capfirst }} | 发布于: {{ stampToDate(post.CreatedTime, "2006-01-02") }}</p>
    </div>
    {% endfor %}
{% endarchiveList %}
</div>

In this example,{% cycle 'primary' 'secondary' as card_theme %}Will alternate generated'primary'or'secondary'Values stored tocard_themeIn the variable, we can use it multiple times at any position in the loop later{{ card_theme }}to refer to this value, for example, to affectdivofclassandpthe text within the tag.

Summary

cycleThe tag is a simple yet powerful tool in the AnQiCMS template, which enables inforIt's easy to alternate data and style display in loops. Whether for visual beauty or logical data distinction, using it proficientlycycleTags can make your template code more elegant and efficient.


Frequently Asked Questions (FAQ)

1.cycleIs there a limit to the number of parameters a tag can have?

TheoreticallycycleThe tag can accept any number of parameters, it will iterate in the order of the parameters you provide.In practice, to maintain logical clarity and code maintainability, it is usually recommended to use 2 to 4 parameters to achieve common alternating effects.The more parameters, the more complex the loop pattern, and the harder it is to understand.

2.cycleCan a tag alternate the output of variable values instead of fixed strings?

Absolutely.cycleThe label parameter can be any valid template variable. For example, if you have a list containing different URLs['/image1.jpg', '/image2.jpg'], you can directly incycleUsed in tags{% cycle imageUrl1 imageUrl2 %}Alternately output these image URLs. It will alternate based on the actual value of the variable in the current loop iteration.

3. How tocycleSet a default value in the tag to prevent some parameters from being empty in the loop?

cycleThe tag itself does not have the function of setting default values directly, it will strictly follow the parameters you provide in the loop. If the parameter is a variable and it is empty during some iteration, thencycleThe tag will output an empty string. If you need to provide alternative content for possible null values, you can incycleTagExternalUseifJudgment ordefaultto processcycleThe output of the alias. For example,{{ cycled_value | default:'默认值' }}.

Related articles

How to judge whether the current item is the first or last item in the `for` loop in AnQiCMS template?

In AnQiCMS template development, we often encounter situations where we need to display data in a list loop, such as article lists, product categories, navigation menus, etc.In these loops, sometimes we need to treat the first or last item in the list specially, such as adding unique CSS styles, displaying different content, or cleverly handling the separators between list items.AnQiCMS uses a syntax similar to the Django template engine, providing us with a very intuitive and powerful tool to solve these common template logic problems.### Core Mechanism

2025-11-09

How to check if the article content in the AnQiCMS template contains specific keywords and display conditions based on this?

In website content operation, we often need to flexibly adjust the display of the page according to the actual content of the article.For example, if an article mentions a specific product or event, we may want to highlight related purchase links or promotional information on the page;If the content of the article involves sensitive topics, it may be necessary to add additional disclaimers.This requirement for conditional display based on article content can be fully realized in the AnQiCMS template.AnQi CMS uses a template engine syntax similar to Django

2025-11-09

How to control the automatic escaping of HTML tags with the `autoescape` tag in AnQiCMS templates?

In the AnQiCMS template system, our daily content display core is inseparable from the handling of HTML tags.To ensure the security of the website, AnQiCMS defaults to automatically escaping variables output in templates.This mechanism effectively prevents the injection of malicious code, such as common cross-site scripting attacks (XSS).However, in some scenarios, we may need to display rich text content that includes HTML tags, at this point we need to understand how to flexibly control this automatic escaping function.### Automatically Escaped

2025-11-09

How can AnQiCMS templates safely display user-submitted rich text content to prevent potential XSS attacks?

During website operations, displaying rich text content submitted by users, such as article comments, forum posts, or blog content, is an unavoidable requirement.However, there may be malicious scripts hidden in these contents, and if they are displayed without precautions, it may lead to cross-site scripting (XSS) attacks, posing potential threats to website visitors.AnQiCMS (AnQiCMS) has fully considered this security risk in its design and provides a series of mechanisms through its template engine to help us safely handle this type of rich text content.

2025-11-09

How to skip certain items in the `for` loop of the AnQiCMS template based on specific conditions?

In AnQiCMS template development, we often need to display a series of contents, such as article lists, product lists, or navigation menus.But often, we do not want to display all the data at once, but rather hope to skip a part of it according to certain specific conditions, making the final content displayed more accurate and in line with the user's needs.AnQiCMS uses a syntax similar to the Django template engine, which provides a powerful and flexible tool for us to implement this conditional skipping.To implement `for`

2025-11-09

How to judge whether a custom field exists in the AnQiCMS template and conditionally render according to its value?

In AnQiCMS template development, flexibly displaying content is the key to improving user experience and website professionalism.Among them, judging custom fields and rendering conditions based on their values is an indispensable skill to achieve this goal.In this way, you can ensure the precise display of page content, avoid displaying empty values, or dynamically adjust the page layout and functionality based on specific data.### Understanding AnQiCMS Custom Fields and Their Retrieval Methods in Templates AnQiCMS is a powerful content management system

2025-11-09

How to determine if the `Content` field of the document is empty using the `archiveDetail` tag and display alternative content?

How can you elegantly handle the case where the document content is empty in AnQi CMS?During the operation of the website, we often publish various types of documents, which contain important information.However, sometimes for various reasons, such as the content is still in draft stage, data is missing during import, or simply some documents are only titled without detailed text, we may encounter the situation where the `Content` field of the document is empty.If the template does not perform any processing when rendering these document detail pages, the user may see a blank page area, which not only affects user experience

2025-11-09

How to safely embed third-party statistics or advertising JS code in AnQiCMS templates?

In website operation, we often need to rely on third-party statistical tools to analyze visitor behavior, or to generate income through advertising platforms.Embed these third-party JavaScript (JS) codes securely and efficiently into website templates is a skill that every website operator needs to master.For those using AnQiCMS, understanding its template mechanism and built-in features can help us complete this task more securely.AnQiCMS is an enterprise-level content management system developed based on the Go language, which has always paid close attention to performance and security in its initial design

2025-11-09