How to define a string array variable directly in the template using the `list` filter?

Calendar 👁️ 72

AnQiCMS with its flexible and powerful template engine provides great convenience for content display.When using templates for front-end development, we often need to handle various data, among which array variables are a common and practical data structure.Many times, we may need to define some fixed or temporary string arrays directly in the template, rather than passing them through backend code each time.Fortunately, AnQiCMS provides a very convenientlistThe filter makes this operation extremely simple.

Core function analysis:listThe role of the filter

listThe primary function of the filter is to convert a string that conforms to a specific format directly into an array variable that can be used in a template. This means that you can convert text that looks like an array throughlistAfter filtering, we get a real array object, and then we can traverse and access it like we would with data obtained from the backend. According to the documentation, this filter will parse a string into a[]string{}An array of types, even if it contains numbers, they will be treated as strings after parsing.

How to use: I'll teach you step by step how to define an array

In AnQiCMS template, to define a string array variable, you need to combinesetTags andlistfilter.settags are used to declare and assign values to variables in the template, andlistThe filter is responsible for converting the string we provide into an array.

The basic syntax structure is as follows:

{% set yourArrayVariable = '["元素1", "元素2", "元素3"]'|list %}

Here are some key points to note:

  1. String format:listThe filter expects to receive a string formatted similar to a JSON array. This means you need to enclose the entire array content within single or double quotes, and array elements are placed within square brackets[and]between.
  2. Element separator: Elements within the array must be separated by English commas,It separates.
  3. Element referenceThe array elements (especially string elements) are best enclosed in single or double quotes, for example"关键词1". Although in some cases quotation marks can be omitted (such as numbers), it is recommended to always use them to maintain consistency and avoid potential parsing issues.
  4. setTag:yourArrayVariableThis is the variable name you define for this array, which will be used to refer to this array in subsequent template code.

Practice exercise: Applying in the templatelistFilter

Imagine you need to display a set of popular tags in the sidebar of a page, and these tags are not many and relatively fixed, or you need to test the display effect of a tag, at this timelistThe filter comes into play.

Let's look at a real example:

{# 使用 list 过滤器定义一个名为 myTags 的字符串数组 #}
{% set myTags = '["安企CMS", "AnQiCMS", "模板技巧", "内容运营", "Go语言", "SEO优化"]'|list %}

<div class="tag-cloud">
    <h3>热门标签</h3>
    <ul>
        {# 遍历 myTags 数组,显示每个标签 #}
        {% for tag in myTags %}
            <li><a href="/search?q={{ tag|urlencode }}">{{ tag }}</a></li>
        {% endfor %}
    </ul>
</div>

<hr>

{# 另一个例子:包含数字的数组,但仍被视为字符串处理 #}
{% set productCodes = '["P-001", "P-002", 123, "P-004"]'|list %}
<p>产品代码列表及元素类型:</p>
<ul>
    {% for code in productCodes %}
        {# 即使定义时是数字,被 list 过滤器处理后,也会作为字符串处理 #}
        <li>{{ code }} (类型: {{ code|stringformat:"%T" }})</li>
    {% endfor %}
</ul>

In this example:

  • We first usesetTags andlistThe filter defines a namedmyTagsarray that contains several string tags.
  • Then, we useforLoop throughmyTagsarray, for each element (tag) for processing.
  • In the link, to ensure the correctness of the URL parameters, we also usedurlencodeThe filter encoded the tag content.
  • The second example shows, even if the array contains numbers123AfterlistAfter the filter has processed,code|stringformat:"%T"It will also show its type asstringThis proveslistThe filter will uniformly handle all elements as strings.

Application scenarios: When to uselistFilter?

listThe filter is powerful, but it is most suitable for specific application scenarios:

  • Fixed small list displayWhen you need to display a small, fixed list of items on the page (such as the friend link categories at the bottom of the website, some preset filtering conditions, etc).
  • Temporary data structureWhen performing some simple logical judgments or data combinations in the template, it is necessary to temporarily store a group of strings.
  • Template development debugging: In the early stages of developing the template, when the backend data is not ready, you can uselistthe filter to quickly simulate some data for testing page layout and loop functions.
  • configuration options: Store a small amount of configuration options that do not need to be frequently changed through the database, such as some color codes, icon names, etc.

Cautionary notes and **practice

  • Strict format: Make sure to pass inlistThe string of the filter strictly follows the format of a JSON array, otherwise it may cause parsing failure or unexpected results.
  • Type uniform:listThe filter will treat all parsed elements as strings. If your business logic has strict requirements for data types (such as performing mathematical operations), then these elements may need to be converted to the appropriate type when accessed (for example, usingintegerorfloatFilter, but it's best to handle the type on the backend).
  • Data volume limit:listThe filter is suitable for processing small-scale static data. For large amounts of dynamic data or data that requires complex queries, it is still recommended to retrieve and pass data to the template through the backend controller to ensure performance and code maintainability.
  • readability:Although it is possible to define an array directly in the template, it is recommended to use this method only when the array content is short and does not involve complex logic.

MasterlistThe filter will make you more proficient in AnQiCMS template development, allowing you to flexibly deal with various front-end data display needs.


Frequently Asked Questions (FAQ)

  1. Q:listCan the filter-defined array contain different types of data (such as numbers, boolean values)?A: It can be included syntactically, butlistThe filter will parse all elements and treat them as string type. This means that even if you defined'["apple", 123, true]'|listaccessing123andtruein the template, they are still strings."123"and"true".

  2. Q: How do I traverselistWhat array is defined by the filter?A: After defining the array, you can traverse it like any other array or slice, using the AnQiCMS template engine providedforLoop the tag to iterate over it. For example:{% for item in yourArrayVariable %}{{ item }}{% endfor %}.

  3. Q:listWhat is the difference between a filter and the data retrieved from the database, which one should I choose?A:listThe filter is mainly used to define and use small-scale, static string arrays directly in templates, such as fixed option lists or test data.Data from the database is usually used to process large-scale, dynamically generated data that requires persistent storage.Choose which way depends on your data characteristics: if the data volume is small, fixed and does not need to be persisted,listThe filter is more convenient; otherwise, it should be obtained through the backend to access the database data.

Related articles

How does the `linenumbers` filter add line number markers to each line of multiline text?

In website content display, sometimes we need to add line numbers to specific multi-line text content, such as code examples, step-by-step tutorials, or log information, to enhance readability and facilitate reference.AnQiCMS provides a simple and practical template filter `linenumbers`, which can help us easily achieve this function. ### The `linenumbers` filter's purpose The `linenumbers` filter is specifically used to automatically add line number markers to each line of multi-line text.It will start from the number 1

2025-11-08

How do the `linebreaks` and `linebreaksbr` filters convert newline characters in multi-line text to HTML's `<p>` or `<br/>` tags?

When managing content in Anqi CMS, we often encounter such situations: when the multi-line text entered in the background editing box is displayed on the front-end page, it becomes a single line, or the newline characters are displayed as text.This is because the browser ignores single newline characters (`\n`) by default when rendering HTML.If you want the content to be displayed with paragraph breaks or line breaks like in the editing box, you need to rely on the powerful template filters provided by AnQiCMS, especially `linebreaks` and `linebreaksbr`

2025-11-08

How to get the length of a string, array, or key-value pair in the `length` and `length_is` filters of the Anqi CMS template?

In Anqi CMS template development, it is often necessary to dynamically adjust the display of the page according to the length of the data content.Whether it is to truncate text, judge whether the list is empty, or perform simple content verification, understanding how to obtain the length of strings, arrays, or key-value pairs is the foundation of these functions.AnQi CMS provides the `length` and `length_is` filters, which can help developers flexibly handle these requirements.

2025-11-08

How does the `join` filter concatenate elements of an array into a single string using a specified delimiter?

In Anqi CMS template design, we often encounter the need to integrate a series of data items into a coherent text.For example, we need to display multiple tags (Tag) in one place, or combine a set of custom parameter values obtained from the database.At this point, the `join` filter comes into play, which can efficiently concatenate the elements of an array into a string with the specified separator.### Understand `join`

2025-11-08

How does the `phone2numeric` filter convert letters on a mobile phone's numeric keypad to the corresponding numbers?

In AnQiCMS template development, we often need to handle various data, and sometimes we may encounter some special situations with phone number input and display.For example, some phone numbers include letters (also known as "pretty numbers" or "vanity numbers", such as 1-800-FLOWERS) for ease of memorization or brand promotion.However, when dialing in practice, these letters need to be converted to the numbers on the corresponding number keypad.AnQiCMS provides a very practical built-in filter——`phone2numeric`, which helps us easily complete this conversion

2025-11-08

How to use the `random` filter in Anqie CMS template to randomly return a character or value from a string or array?

In AnQi CMS template development, sometimes we hope to add a touch of dynamism and surprise to the website content, so that visitors can see different elements each time they refresh the page.This is a very practical tool, the `random` filter.It can help us randomly select one from a set of predefined data to display, whether it is randomly selecting characters from a string or randomly selecting a value from an array (or list), it can be easily achieved.

2025-11-08

How do the `removetags` and `striptags` filters remove specified or all HTML tags when processing HTML content?

In the daily content operation of AnQi CMS, we often encounter situations where we need to handle HTML content.To display plain text summaries in specific scenarios, or to standardize content output and enhance security, removing HTML tags is a common requirement.AnQi CMS provides two very practical template filters: `removetags` and `striptags`. They each have unique purposes and application scenarios, let us delve into how they help us efficiently clean HTML content.###

2025-11-08

How does the `repeat` filter output a string repeated a specified number of times?

During the process of website content creation, there are times when we have the need to output a specific string multiple times, such as for visual separation, placeholder content, and quick generation of list items.In the AnQiCMS template system, the `repeat` filter provides a very practical function that can help us complete this task efficiently.This filter, as the name implies, repeats a string according to the number we specify, thus saving the trouble of manual copying and pasting, greatly enhancing the efficiency and flexibility of template writing.###

2025-11-08