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)
- 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