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 through
forGenerate 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, by
forLoop 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 corresponding
optionorinputelements.
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 `