In AnQiCMS template development, flexibly handling and displaying data is the key to enhancing the expression of website content.We often encounter such a scenario: receiving a string containing multiple pieces of information from the backend, such as keywords of articles or features of products, which may be separated by commas or other symbols.If it is possible to split these strings into independent segments and process each segment separately, it can greatly enhance the flexibility of the template and the dynamism of the content.
Today, let's delve into how to cleverly utilize the templates in AnQiCMS{% set %}Tags andsplitFilter, split strings into an array of operable items and assign them to a new variable, thus achieving more refined content control.
{% set %}Tag: define your exclusive variables
Firstly, let's understand it.{% set %}Label.In AnQiCMS template syntax, it plays a very important role, allowing you to define and assign variables within the template.This is like declaring a local variable when writing a program, you can assign any data, whether it's a string, number, or list, object, to a custom variable name and use it in the subsequent parts of the current template.
Use{% set %}The basic syntax is very intuitive:
{% set myVariable = "这是一个字符串" %}
<p>{{ myVariable }}</p>
Here, we created a name ofmyVariableThe variable, and it assigned a string. The scope of this variable is limited to the current template, which can help us store intermediate results and make the template code more readable and maintainable.
splitFilter: The Tool for Cutting Strings
Next, let's introduce another main character of ours -splitFilter. As the name suggests,splitThe main function is to split a string into an array of strings (or a slice in Go) according to the delimiter you specify.
Imagine you have a list of comma-separated keywords: "SEO, content marketing, website optimization". If you want to display them as clickable tags, thensplitFilter is the tool you need.
splitThe usage of filter is as follows:
{% set tagsString = "SEO,内容营销,网站优化" %}
{% set tagsArray = tagsString|split:"," %}
{# 此时 tagsArray 就是一个包含三个元素的数组:["SEO", "内容营销", "网站优化"] #}
Here are a few points to note:
- Separator:
splitA filter requires a string as a delimiter. In the above example, we used a comma,. - The delimiter does not exist.If the original string does not contain the specified delimiter,.
splitThe filter will return an array containing the original string as the only element. - Empty delimiter:If the delimiter is an empty string
"",splitThe filter will split each character in the string into an element of the array.
Core Practice:{% set %}WithsplitPerfect combination of filters
Now, let's take{% set %}andsplitThe filter combines to create a more practical scenario: Suppose your article detail page has aarchive.KeywordsThe field contains a string similar to 'Keyword A, Keyword B, Keyword C', and you want to split these keywords and generate a link tag for each keyword.
{# 1. 获取文章的关键词字符串 #}
{% set rawKeywords = archive.Keywords %}
{# 2. 使用 split 过滤器将字符串按逗号切割成数组,并赋值给新变量 keywordList #}
{% set keywordList = rawKeywords|split:"," %}
<div class="article-tags">
<span>相关标签:</span>
{% if keywordList %} {# 检查数组是否为空,避免空内容显示 #}
<ul>
{% for keyword in keywordList %}
{# 3. 遍历数组,并为每个关键词生成链接 #}
{# - trim 过滤器用于移除关键词两边的空格,因为分割后可能存在 " 关键词B" 这样的情况 #}
{# - urlencode 过滤器用于将关键词编码,确保作为URL参数时不会出现问题 #}
<li><a href="/tag/{{ keyword|trim|urlencode }}">{{ keyword|trim }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>暂无相关标签。</p>
{% endif %}
</div>
In this example, we first use{% set rawKeywords = archive.Keywords %}Obtained the original keyword string. The next critical step is{% set keywordList = rawKeywords|split:"," %}it has completed the string splitting, and the split string array has been assigned tokeywordListthis new variable.
Then, we use a{% for %}to iteratekeywordListEvery keyword in the array. Inside the loop, to provide a better user experience and SEO-friendliness, we also cleverly combinetrimFilter to remove any leading and trailing spaces that may exist in keywordsurlencodeFilter to ensure that the generated tag links are valid and standardized
More application scenarios and techniques
This{% set %}CombinesplitThe pattern, widely used in AnQiCMS template development, has great application value:
- Product attribute listIf a field in the product model stores multiple attributes (such as "color:red, size:M, material:cotton"), you can first use
splitSplit each property pair and then further process each property pair. - User-defined fieldWhen the user enters multiple-value information in the custom field in the backend, you can display it flexibly on the front end in this way.
- Image URL list processingIf a field stores multiple image links separated by a specific character, they can be cut and displayed in a gallery in a loop.
Summary
AnQiCMS 强大的模板引擎提供了极大的灵活性,而{% set %}Tags andsplitThe combination of filters is one of the keys to unlocking these potentials.By converting complex string data into an easy-to-process array, you can make your website content more dynamic and refined. Whether it's building a beautiful tag cloud, clear product parameters, or achieving other personalized content layouts, it will become a breeze.Master these fundamental and powerful skills to help you better utilize AnQiCMS to manage and present your website content.
Common Questions (FAQ)
Q1: Ifsplit过滤器指定的分隔符在字符串中不存在,会发生什么?
A1: If the specified delimiter does not exist in the string,splitthe filter will return an array containing the original string as the only element. For example,"AnQiCMS"|split:","you will get a["AnQiCMS"]The array. When iterating over it, it still treats it as a single element, you can use{% if variable %}to check if the array is empty, thus avoiding unnecessary output.
Q2:splitFilter the array elements after slicing, if the element itself contains spaces, how should I deal with it?
A2: InsplitFilter cuts the string, if there are spaces before and after the separator in the original string (for example"SEO , 内容营销"), the cut elements may also contain these spaces (}"SEO "and" 内容营销")。To get clean elements, you can use an extra filter while traversing the array. For example:trim过滤器来去除首尾空格。For example:{{ keyword|trim }}.
Q3:splitCan the filter handle non-string data types (such as numbers)?
A3:splitThe filter is designed to handle strings.If you try to apply it to non-string data types (such as a number), it will usually first try to convert the data to a string and then split it.splitBefore the filter, make sure that your input data is already of string type. If you need to operate on numeric arrays, you may need to consider other methods or data preprocessing on the backend.