How to define an array and display its content in the template using the AnQiCMS filter?

Calendar 👁️ 77

Advanced Template Development: Flexibly Define and Display Array Content in AnQiCMS Template

During the template development process of AnQiCMS, we often encounter scenarios where we need to handle list data on the front-end page, dynamic configuration options, or generate a series of contents based on specific logic.Although most of the data is obtained through tags from the backend, in some cases, defining and operating on simple data sets directly in the template, especially arrays, can greatly improve the flexibility and efficiency of front-end development, and reduce dependence on backend data.AnQiCMS is a powerful template engine that provides a variety of filters, allowing you to easily define arrays in templates and display their content.

Understanding Filterers and Variable Definitions in AnQiCMS Templates

AnQiCMS's template system is based on Django-like syntax, its core lies in outputting data through double curly braces{{ 变量 }}and through{% 标签 %}To implement logical control. Filters are important tools in the template language for processing variable output, and they use the pipe symbol|Applied to variables, for data transformation or processing. At the same time,{% set %}Tags allow us to define variables within the template, which provides the foundation for defining arrays.

Define an array in the template: two commonly used filters

To define an array in the AnQiCMS template, you can mainly make use oflistFilters andsplitfilters. They are suitable for different scenarios.

1. UselistFilter from JSON string to define an array

listA filter can convert a string that conforms to the JSON array format into a template-iterable array (typically a string slice at the bottom)[]string{}This approach is suitable for defining structured, fixed, or preset array content.

Usage:

You need to provide the array content in the form of a JSON string.listA filter. For example, if you want to define an array containing several colors:

{% set colors = '["red", "green", "blue", "yellow"]'|list %}

Here, '["red", "green", "blue", "yellow"]'is a standard JSON array string.|listThe filter parses it and assigns it tocolorsVariables. Even if the array contains numbers, they will be treated as strings.

2. UsesplitThe filter defines the array from the delimiter string.

splitThe filter is used to split a string into an array according to a specified delimiter.This method is very convenient for processing some string data provided by the backend, which is separated by specific characters (such as commas, bars, etc.), or for quickly defining short lists in templates.

Usage:

You need to provide a string to be split and specify the delimiter.

{% set fruits = "apple,banana,orange,grape"|split:"," %}

In this example, the string"apple,banana,orange,grape"it will be,Split a delimiter into an array containing four fruit names and assign it tofruitsthe variable. If you need to split by space, the delimiter can be simply specified as" "If the delimiter is an empty string""It will split by each UTF-8 character (including Chinese characters).

AnQiCMS also providesmake_listFilter, function withsplitA filter similar to it, but it will split each character of the string into an element of the array, which is also very friendly for processing Chinese character strings.

{% set characters = "你好世界"|make_list %}

Display the content of the array:forLoop and index access

Once you define an array in the template, you can iterate over it to display its content. In scenarios where you need to access specific elements, you can also access them directly by index.forFor specific element access scenarios, you can access them directly by index.

1. UseforLoop through the array

forLoop is the most commonly used way to traverse an array. It allows you to access each element of the array one by one and process each element within the loop body.

Usage:

<p>我喜欢的颜色有:</p>
<ul>
{% for color in colors %}
    <li>{{ color }}</li>
{% endfor %}
</ul>

In the above example,colorsEach element in the array ("red", "green", etc.) will be assigned tocolorvariables and displayed in<li>tags.

forThe loop also provides some built-in variables, such asforloop.CounterYou can get the current loop index (starting from 1),forloop.RevcounterYou can get the remaining number of times in the current loop.

<p>水果列表:</p>
<ol>
{% for fruit in fruits %}
    <li>第 {{ forloop.Counter }} 种水果:{{ fruit }}</li>
{% endfor %}
</ol>

Handle empty array:If the array may be empty, you can use{% empty %}Label to define the alternative content displayed when the array is empty to enhance user experience.

<p>今天的特价菜:</p>
<ul>
{% for dish in special_dishes %}
    <li>{{ dish }}</li>
{% empty %}
    <li>今日暂无特价菜。</li>
{% endfor %}
</ul>

2. Access array elements directly by index.

If you need to access a specific element in the array instead of traversing the entire array, you can use square brackets[]by adding the index number to access it directly. The index starts from0.

<p>我的第一个最爱颜色是:{{ colors[0] }}</p>
<p>我最不喜欢的颜色可能是:{{ colors[3] }}</p>

Please note that if you try to access an index beyond the array range, the template engine may throw an error or return an empty value, so it is recommended to make necessary judgments before using it in a production environment.

Examples of actual application scenarios

  • Dynamically generate a navigation menu or filter conditions:You can define an array containing navigation names and links in the template, then throughforGenerate menu items dynamically in a loop to avoid frequently creating individual navigation in the background.
  • Toggle theme styles or icons:Define an array containing CSS class names or icon paths, byforLoop combination{% cycle %}Tags, to implement alternating styles for elements, such as the zebra striping effect of table rows.
  • Configure simple form options:For some infrequently changing dropdown menu or radio button options, you can directly define an array in the template and then generate the correspondingoptionorinputelements.

Combined with other filters: more operations on arrays

Once the array is defined, you can also combine it with other filters provided by AnQiCMS to achieve more complex data processing:

  • joinFilter:Concatenate array elements into a string.
    
    {% set tags = "AnQiCMS,GoLang,CMS"|split:"," %}
    <p>文章标签:{{ tags|join:" | " }}</p> {# 输出: AnQiCMS | GoLang | CMS #}
    
  • containFilter:Check if the array contains a specific element.
    
    {% set user_roles = '["admin", "editor"]'|list %}
    {% if user_roles|contain:"admin" %}
        <p>您是管理员。</p>
    {% endif %}
    
  • sliceFilter:Slice the subset of the array.
    
    {% set all_items = "item1,item2,item3,item4,item5"|split:"," %}
    {% set first_three = all_items|slice:":3" %} {# 获取前三个元素 #}
    {% for item in first_three %}
        <span>{{ item }}</span>
    {% endfor %}
    

Summary

BylistandsplitAnd filters are defined in the AnQiCMS template array, and combinedforLooping and index access to display its content, which can bring great convenience to front-end development.This method can not only handle simple list data, but also realize flexible configuration and dynamic content generation within the template without increasing the burden on the backend.Master these skills and it will make your AnQiCMS template development more efficient and powerful.


Frequently Asked Questions (FAQ)

Q1:listorsplitDoes the filter support defining an array containing different types of data, such as both numbers and strings? A1: listandsplitThe filter is mainly used to create in the AnQiCMS template `

Related articles

How to extract a specified part of a string or array for display in the AnQiCMS template?

In AnQiCMS template development, we often encounter the need to handle string or array content, such as displaying article summaries, limiting the number of image lists, or extracting specific information from a long text.The AnQi CMS is developed based on the Go language, its template engine supports syntax similar to Django and Blade, and provides a rich set of filters (filters) to help us efficiently complete the content extraction and display requirements.Let's take a look at how to flexibly extract the specified part of a string or array for display in the AnQiCMS template.

2025-11-07

How to link array elements into a string for display in AnQiCMS template?

In AnQiCMS template development, we often encounter situations where we need to display a series of related data, such as multiple tags of an article, various characteristics of a product, or multiple options stored in a custom field.These data are often present in the template in the form of an array, and we hope to display them in a concise and beautiful string format, such as connecting them with commas, slashes, or other symbols.

2025-11-07

How to convert a numeric string in AnQiCMS template to a floating-point number or integer for display?

In AnQiCMS template development, data processing is one of the core links.The flexible content model allows us to customize various fields to store website information, including scenarios where numbers are needed, such as product prices, inventory quantities, ratings, and so on.Although these numbers may look normal in the background, they are likely to be presented as strings when called in the template.This brings up a common question: How can we convert these numeric strings to floating-point numbers or integers in a template for mathematical operations or specific formatting?

2025-11-07

How to remove the specified characters from a string in the AnQiCMS template to optimize display?

In website operation, the clarity of content presentation and user experience are crucial.Sometimes, the content we enter from the background or the fields we retrieve from the database may contain some unnecessary characters, such as extra spaces, specific delimiters, or leading text that needs to be cleaned up, all of which may affect the aesthetics of the page and the readability of the content.

2025-11-07

How to automatically wrap long text in AnQiCMS templates for optimized reading experience?

In website content operation, optimizing the reading experience is a key factor in attracting and retaining users.Especially for long text content, if there is a lack of proper formatting and automatic line breaking, users may face issues such as horizontal scrolling and text stacking, which can severely affect reading comfort and even lead to user loss.As an AnQiCMS user, we can take advantage of its powerful template engine and built-in features to easily implement automatic line breaks in long text, thereby greatly enhancing the reading experience of the website content.## The Importance of Understanding Long Text Line Breaks Imagine browsing an article on your phone

2025-11-07

How to format floating-point numbers and retain a certain number of decimal places in AnQiCMS templates?

In website content operation, we often need to display floating-point numbers such as prices, percentages, ratings, and so on.The precision and display method of these numbers directly affect the user experience and the professionalism of information.AnQi CMS knows this need and provides a powerful and flexible floating-point number formatting function in the template engine, allowing you to easily control the display accuracy of floating-point numbers.Next, we will explore two main methods of formatting floating-point numbers and retaining specified decimal places in AnQiCMS templates: the `floatformat` filter and the `stringformat` filter

2025-11-07

How to get the thumbnail of AnQiCMS image resources and display it?

AnQiCMS focuses on visual effects and page loading efficiency in content display, therefore, how to efficiently obtain and display thumbnail images of image resources is a common problem we encounter in daily operations.It is fortunate that AnQiCMS provides a very convenient and flexible way to handle image thumbnails, allowing us to easily meet various display needs. --- ### How to manage and generate image thumbnails in AnQiCMS?

2025-11-07

How to parse and output HTML code in AnQiCMS template instead of escaping it?

When using AnQi CMS for website content creation and template design, we often encounter a problem related to HTML code display: Why is the HTML code I enter in the background editor displayed as plain text on the front page instead of being parsed by the browser as actual HTML elements?This is actually the content management system that defaults to enabling HTML content escaping for website security.This article will delve into how to effectively control the output of HTML code in the AnQiCMS template, ensuring that it is parsed correctly and not displayed as escaped.

2025-11-07