What are the benefits of directly defining an array (`list`) in the AnQiCMS template? How to define it?

Calendar 👁️ 77

In AnQiCMS templates, we often encounter scenarios where we need to display some small, relatively fixed list data, such as the featured functions of a page, the advantages of a product series, or auxiliary navigation links, etc.The traditional method may require creating a special content model on the back end, then publishing several pieces of data, and finally calling it through template tags.But this seems somewhat cumbersome for data that does not change frequently and is limited in quantity.

In order to handle such requirements more efficiently and flexibly, AnQiCMS provides a way to define arrays directly in the template (listA convenient way, it can help us simplify the development process, making the template more expressive.

What are the benefits of defining an array directly in the template?

Define arrays directly in the AnQiCMS template, mainly bringing the following conveniences:

first, Improve development efficiency and iteration speed.For some page-specific, small content lists that do not involve database storage, we can quickly define and render them directly in the template file.This means there is no need to log in to the backend to create content models, publish content, which greatly shortens the development cycle, especially when the front-end page needs to frequently adjust these small lists, you can directly modify the template file, take effect immediately, greatly improving work efficiency.

secondly,Enhance the flexibility and self-sufficiency of the template.In some cases, we may need to temporarily define a set of options or data based on the requirements of a specific page or component, such as filter conditions for a module, a set of fixed icon class names, etc.Embed these data directly into the template, which can help the component better encapsulate its logic and data, reduce dependence on global configuration or backend data, and make the template itself more modular and portable.

Moreover,Simplify data management and reduce maintenance costs.If all list data is managed through the background content model, even a small amount of fixed and unchanging data will consume database resources and may increase the complexity of background management.By defining arrays in the template, we can differentiate this "lightweight" data from "heavyweight" content (such as articles, products), making the backend focus on core content management, and also making the template structure clearer, easier to understand, and maintain.

Finally,Ease rapid prototyping and testing.At the early stage of template development, real data may not be ready.Define the mock data array directly in the template, which can quickly build the page skeleton and functions, conduct style and interaction testing, and then replace it with dynamic data after the backend data interface is perfected for a smooth transition.

How to define an array in AnQiCMS template?

In AnQiCMS, with its powerful filter function, we can easily define an array in the template. This is mainly throughsetLabel collaborationlistTo implement a filter.

Define the basic syntax of the arrayThat's it:

{% set 变量名称 = '["元素1", "元素2", "元素3", ...]'|list %}

Let's take a detailed look at this syntax:

  • {% set 变量名称 = ... %}This is a tag used in AnQiCMS templates to define variables. You can变量名称Replace it with any meaningful name you want, such asmyFeatures/navItemsetc.
  • '["元素1", "元素2", "元素3", ...]'This is the string format of defining array content. It needs to be enclosed in single or double quotes to indicate that it is a string. The elements of the array are enclosed in square brackets inside the string.[]Enclosed, elements separated by English comma,Separate. Each element itself can also be enclosed in quotes (especially when the element is a string), but quotes are optional for types such as numbers.
  • |listThis is the key.listA filter. Its purpose is to parse and convert the previously defined string into an array (under the hood in Go, it is handled as a[]string{}type, that is a string slice).

Define an array exampleYou can try it like this:

{# 定义一个包含特色功能的数组 #}
{% set myFeatures = '["高效管理", "灵活定制", "安全稳定", "易于扩展"]'|list %}

{# 定义一个包含图片URL的数组 #}
{% set imageGallery = '["https://en.anqicms.com/uploads/img1.jpg", "https://en.anqicms.com/uploads/img2.jpg", "https://en.anqicms.com/uploads/img3.jpg"]'|list %}

{# 定义一个包含混合类型(但最终都会被视为字符串)的数组 #}
{% set mixedData = '["AnQiCMS", 2023, true, "GoLang"]'|list %}

After defining the array, we can use it flexibly in the template.

The most common usage is to cooperate withforLoop to iterate over the array, display each element:

<div class="features-list">
    <h3>我们的核心优势:</h3>
    <ul>
        {% for feature in myFeatures %}
            <li>{{ feature }}</li>
        {% endfor %}
    </ul>
</div>

If you need to access a specific element in the array, you can use an index (starting from 0):

<p>第一个特色功能是:{{ myFeatures[0] }}</p>
<img src="{{ imageGallery[1] }}" alt="第二张图片">

It is worth noting that, due tolistThe filter will convert all elements to string type, even if you define numbers or boolean values, they are still strings in the template. For most display needs, this will not cause any trouble, but if you want to perform arithmetic operations on numbers, you may need to use other filters such as|integeror|floatPerform an explicit conversion.

In general, the AnQiCMS feature of directly defining arrays in templates provides us with a lightweight, efficient data processing method, making template development more convenient, and also allowing for more flexible and diverse presentation of website content.


Frequently Asked Questions (FAQ)

1. What are the data types of array elements defined in the template?

When you use AnQiCMS template,|listWhen defining an array filter, regardless of whether you write numbers, boolean values, or other data that looks like different types in the string, they will ultimately be processed by the system as strings([]string{}This means that even if you defined'["123", 456]'|listto accessmyArray[1]the value obtained at the time"456"It is still a string, not an integer. For most display needs, this is usually fine, but if you need to perform mathematical calculations, you may need to use it first.|integeror|floatConvert using filters.

Can the array defined in this way be queried or filtered complexly like background data?

Not allowed.The array defined directly in the template is static, its values are determined at the time of template parsing, and it does not support complex dynamic queries, sorting, or filtering, nor does it support advanced operations such as pagination.This method is more suitable for displaying fixed, finite list data.archiveList/categoryListto call.

3. Can I define multiple arrays in a template?

Of course you can.You can define as many arrays as needed within the same template file, just make sure each array uses a different variable name.myFeatures/imageGalleryandsocialLinksMultiple arrays are used, and they are called and displayed in different parts of the template. This flexible definition method allows you to better organize and manage various small static content blocks on the page.

Related articles

How does the `add` filter implement flexible connection of text content?

In the Anqi CMS template world, we often need to dynamically combine different content blocks or data, whether it is the sum of numbers or the concatenation of text.At this time, the `add` filter acts as a flexible bridge, helping us easily achieve content concatenation, making the website display more vivid and personalized. ### Deep Understanding of `add` Filter: The Bridge Between Text and Data The `add` filter is a very practical feature in the Anqi CMS template engine, whose core function is to perform addition of numbers and concatenation of strings.It lies in its intelligent processing style

2025-11-08

How to format numbers or variables into a specified string format: common applications of the `stringformat` filter?

In the template development of Anqi CMS, we often need to display various data obtained from the background in a specific and beautiful format to website visitors.Whether it is the price of goods, the reading volume of articles, or the balance of users' points, the original presentation of data may not always be ideal.This is when the `stringformat` filter becomes a very useful tool.The `stringformat` filter helps us to format numbers, variables, and even more complex structures according to the predefined string pattern and output them.In short

2025-11-08

`trim`, `trimLeft`, `trimRight` filters specific usage scenarios and differences in AnQiCMS templates?

In AnQiCMS template development, handling and optimizing the display of page content is one of the daily tasks.We often need to process the data obtained from the backend to ensure that it is neat and meets expectations on the frontend.Among them, the cleaning of strings, especially the removal of redundant whitespace characters or specific characters, is a key factor in improving content quality and user experience.The AnQiCMS template system provides several very practical filters: `trim`, `trimLeft`, and `trimRight`.They each have their own unique uses and application scenarios.

2025-11-08

Remove extra spaces or specific characters from a string, which filter should be used first (`cut` or `trim`)?

In the template world of Anqi CMS, we often need to clean and format strings, such as removing extra spaces from user input or dealing with specific symbols mixed in with imported content from external sources.At this point, the `cut` and `trim` filters have become our reliable assistants.Although they can all 'remove characters', their working methods and applicable scenarios are fundamentally different.Understanding the difference between these two can help us handle content more efficiently and accurately, making the website display more professional and tidy.

2025-11-08

How to determine if a string contains a substring in AnQiCMS template?

In AnQiCMS daily operation and template design, we often need to decide how to display it based on the specific attributes of the content.For example, you may want to highlight articles that contain a certain keyword in the title, or adjust the style based on whether there is a specific phrase in the product description.How to determine whether a string contains another substring in a template has become a very practical skill.AnQiCMS's template system is based on the Django template engine syntax, providing a rich set of tags and filters to help us flexibly process data.for string inclusion judgment

2025-11-08

The role of the `count` filter in template data analysis for counting the occurrence of substrings?

In content operation, data analysis is an indispensable link.It can help us understand user behavior, evaluate content effectiveness, and guide future content strategy.AnQi CMS, with its flexible template engine syntax, provides us with powerful data processing capabilities, allowing us to perform some basic and practical data analysis directly at the template level.Among them, the `count` filter is like an efficient 'data detective' that helps us quickly understand the frequency of specific elements in the template data.Understand and make good use of this filter, it will greatly enhance our accuracy in content presentation and strategy formulation

2025-11-08

How to safely display rich text content containing HTML tags in AnQiCMS templates?

In website operation, we often need to display text content containing rich formats and interactive elements, which is what we usually call rich text.This content may contain bold, italic, links, images, and even tables with HTML tags.How can one ensure that these HTML tags are rendered correctly in the AnQiCMS template while also taking into account the website's security, which is a topic worth discussing.### Understand the default security mechanism of AnQiCMS template Firstly, we need to understand one of the core security designs of the AnQiCMS template system: by default

2025-11-08

The `safe` filter: when to use, what potential security risks need to be paid special attention to?

During the template development process of Anqi CMS, the way content is displayed is flexible and diverse, and one of the very important filters is `safe`. Understanding the working principle of the `safe` filter, when to use it, and the security considerations it may bring, is crucial for building a website that is both functional and secure. ### The core function of the `safe` filter First, let's understand a basic security mechanism of the Anqi CMS template engine: the default automatic escaping.

2025-11-08