How to dynamically define and use small array variables for loops in AnQiCMS templates?

Calendar 👁️ 60

In AnQiCMS template development, we often need to flexibly display some small data sets according to business logic.These collections may be some custom tags, navigation items, or just some status indicators.Although AnQiCMS provides rich tags to call back-end data, sometimes we hope to define a small array directly in the template and process it in a loop to achieve finer control and more concise template code.

AnQiCMS's template engine syntax is similar to Django, providing an intuitive and powerful way to operate data. It mainly uses variable assignment tags when defining and using small arrays for iteration in templatessetAnd a very usefullistfilter, combinedforLoop tags, you can easily achieve this requirement.

Understand the variables and loop mechanism in AnQiCMS templates

Variables in AnQiCMS templates are output through double curly braces{{ 变量名 }}While control structures, such as conditional judgments and loops, use single curly braces with a percentage sign{% 标签 %}The form. When we talk about loops, we usually mean{% for item in collection %} ... {% endfor %}such a structure, which will iteratecollectioneach element of this collection, and access them withitemvariables inside the loop.

The key is how to generate this “collection(set). In most cases,“collectionMay come from the document list, category list, etc. passed from the background.But if we want to create a simple array on the fly in the template for looping, we need some additional tricks.

Dynamically define a small array variable:“setwith the tag andlistFilter

The AnQiCMS template engine allows us to usesetLabels define variables in the template. Its basic syntax is{% set 变量名 = 值 %}. This value can be the result of any expression.

To define an array, we can cleverly uselistfilter.listThe filter can convert a string that conforms to the JSON array format into an array type that the template engine can recognize. CombinedsetLabel, we can dynamically define a small array in the template.

For example, if you want to define an array containing several navigation names, you can do it like this:

{% set myNavItems = '["首页", "产品展示", "新闻中心", "联系我们"]'|list %}

In this line of code:

  • {% set myNavItems = ... %}: We declare a variable namedmyNavItems.
  • '["首页", "产品展示", "新闻中心", "联系我们"]'This is a common string, but its content conforms to the format of a JSON array, using brackets[]enclosed, elements are separated by commas,separated, string elements are enclosed in double quotes"".
  • |listThis islistA filter that will parse the preceding JSON-formatted string into a real array object and assign it tomyNavItems.

Thus,myNavItemsIt becomes an array variable that can be used in subsequent templates.

This is not just a simple array of strings, you can also define arrays containing complex data structures (such as objects) as long as they conform to the JSON format:

{% set productTypes = '[{"name": "电子产品", "code": "digital"}, {"name": "家居用品", "code": "home"}, {"name": "图书音像", "code": "books"}]'|list %}

Now,productTypesA variable contains an array of three objects, eachnameandcodeProperty.

Using array variables in loops: practical scenarios and techniques

Once we define a small array variable, we can apply it toforloop to achieve various flexible display needs.

Scenario one: Generate custom navigation menus or filter buttons

Suppose you want to display several fixed links in the sidebar and highlight the link corresponding to the current page.

{% set navItems = '[{"text": "首页", "path": "/"}, {"text": "关于我们", "path": "/about"}, {"text": "联系方式", "path": "/contact"}]'|list %}

<nav class="sidebar-nav">
    <ul>
    {% for item in navItems %}
        <li {% if url.Path == item.path %}class="active"{% endif %}>
            <a href="{{ item.path }}">{{ item.text }}</a>
        </li>
    {% endfor %}
    </ul>
</nav>

In this example,url.Pathis a global variable representing the URL path of the current page. By comparingitem.pathwithurl.Pathwe can easily add the corresponding navigation item for the current page.activeclass to achieve highlighting effect.

Scene two: Dynamically generate status tags or markers

You may need to display a series of states or tags for certain content, such as adding a tag cloud to the article detail page or adding attribute tags to the product list page.

{% set articleTags = '["网站优化", "内容营销", "SEO", "用户体验"]'|list %}

<div class="article-tags">
    <span>相关标签:</span>
    {% for tag in articleTags %}
        <a href="/tag/{{ tag }}" class="tag-badge tag-{{ forloop.Counter }}">{{ tag }}</a>
    {% endfor %}
</div>

Here we made use offorloop.CounterThis built-in variable represents the current iteration count (starting from 1). By adding it to the CSS class name, you can implement differentiated styles based on the index, for exampletag-1/tag-2etc.forThe loop also providesforloop.Revcounter(Count down) and more built-in variables to control loop behavior, making template logic more flexible.

In this way, we can avoid creating a large amount of unnecessary data in the background, or avoid repeating the HTML structure in multiple template files, making the template code more concise and maintainable.

Summary

In AnQiCMS template, dynamically defining and using small array variables for looping is a very practical skill. By combiningsettags for variable assignment andlistThe filter converts a JSON format string into an array, we can create any complex temporary data set. Subsequently, we can useforLoop tags and their built-in variables can easily traverse these arrays to achieve flexible and diverse page display effects.This method not only enhances the flexibility and maintainability of the template, but also allows developers to complete content layout and interaction design more efficiently.


Frequently Asked Questions (FAQ)

  1. Question:listCan the filter only handle strings? What if my array elements are numbers or boolean values?Answer: Yes,listThe filter expects a string as input. But the content of this string can be in any format as long as it conforms to the JSON array format, including various data types such as numbers, boolean values, and even nested objects. For example{% set mixedArray = '[1, "text", true, {"key": "value"}]'|list %}They are fully supported.

2

Related articles

How does the AnQiCMS template automatically convert line breaks in text to HTML tags such as `<p>` or `<br>`?

In website content presentation, text formatting is often the key to determining the user's reading experience.We often encounter such needs: the text content obtained from the background database usually only contains simple newline characters (`\n`), and if it is displayed directly on the web page, the browser will not intelligently convert these newline characters into the HTML paragraph (`<p>`) or line break (`<br>`) tags we expect, causing the content to be cramped together and lose its original structure and readability.AnQiCMS (AnQiCMS) has fully considered this point in template design

2025-11-08

How to get the total length of elements in a string, array, or key-value pair in AnQiCMS template?

In AnQi CMS template design, dynamically obtaining the total length of elements in a string, array, or key-value pair is a very practical feature. It can help us flexibly display information on the page, such as showing the number of products, the number of comments, or adjusting the layout according to the content length.The Anqi CMS template engine provides simple and efficient filters to meet these requirements.### Core Tool: `length` Filter The most direct and universal method to obtain the total number of elements in any string, array (slice), or key-value pair (map/struct) is to use

2025-11-08

How to concatenate the tag array in AnQiCMS template into a string with a custom delimiter?

In AnQiCMS template development, we often need to display a set of data obtained from the database, such as the multiple tags (Tags) of articles, in a user-friendly manner rather than simply listing them.One of the most common needs is to concatenate these tags into a string with a custom separator, such as AnQiCMS's powerful template engine provides a flexible way to achieve this goal.

2025-11-08

In AnQiCMS template, how to convert a string number into an actual `integer` or `float` type?

When working with the Anqi CMS template to display content and make logical judgments, we often encounter situations where we need to perform operations on numbers.However, data obtained from a database or content model, even if it looks like a number in the background, is sometimes passed as a string (``string``) at the template level.If this is directly performed arithmetic operations or numerical comparisons, unexpected results may occur.

2025-11-08

How to convert letter combinations like 'PONGO2' into the corresponding numbers on a phone keypad?

How to easily convert letter combinations to phone number keypad digits in AnQiCMS?In daily life, we sometimes encounter some phone numbers composed of letters and numbers, for example, some companies may use memorable numbers like "999-PONGO2" for brand promotion.However, when making a phone call in reality, these letters need to be converted into the corresponding numbers on the phone keypad.For website operators, if they can automatically complete this conversion on the website front end, it will undoubtedly greatly improve the user experience.

2025-11-08

How to display the singular or plural form of a word based on the quantity value in the AnQiCMS template?

When building a website, we often encounter situations where we need to dynamically display text based on a certain quantity value.For example, when there is '1 comment', we want to display it in singular form; while for '2 comments', it should be displayed in plural form.This detail handling not only improves user experience but also shows the professionalism of the website content.If manual quantity judgment and writing if/else logic make the template code long and difficult to maintain.

2025-11-08

How to safely remove all or part of a specified tag from HTML content in AnQiCMS templates?

When building a website with AnQiCMS, we often need to finely control the content displayed on the page.Especially when dealing with user submitted content, importing articles from different sources, or simply to maintain consistency in page style, you may encounter the hassle of HTML tags.These tags may contain unnecessary formatting, styles, and even potential security risks.Fortunately, the AnQiCMS template system provides a flexible mechanism to help us safely and efficiently remove all or part of the specified tags from the HTML content.

2025-11-08

How to ensure that the multi-site content of AnQiCMS can be displayed and managed uniformly on the front-end?

In today's complex digital environment, many businesses and content creators often need to manage multiple websites, whether they have multiple brand sub-sites, different product line portals, or provide services for multilingual users.How can it be ensured that each site operates independently while also achieving unified display and efficient management of content on the front end, which has become a common challenge.AnQiCMS as an enterprise-level content management system, provides a powerful and flexible solution in this regard.

2025-11-08