In AnQiCMS template development, flexibly handling and displaying data is the key to enhancing the website's content presentation.We often encounter such a situation: we get a string containing multiple pieces of information from the background, such as keywords of articles, feature lists of products, which may be separated by commas or other symbols.If these strings can be cut into independent segments and each segment can be displayed or processed separately, it can greatly increase the flexibility of the template and the dynamics of the content.
Today, let's delve into how to cleverly utilize in AnQiCMS templates{% set %}with the tag andsplitFilter, splits a string into an operable array and assigns it to a new variable, thus achieving finer content control.
{% set %}Label: define your own variable.
First, let's understand{% set %}Label. It plays a very important role in the AnQiCMS template syntax, allowing you to define and assign variables within the template.This is like declaring a local variable when writing a program, where you can assign any data, whether it is a string, number, or a list, object, to a custom variable name and use it in the subsequent part of the current template.
Use{% set %}The basic syntax is very intuitive:
{% set myVariable = "这是一个字符串" %}
<p>{{ myVariable }}</p>
Here, we created a namedmyVariableThe variable is assigned a string. Its scope is limited to the current template, which can help us store intermediate results and make the template code more readable and maintainable.
splitFilter: The Power Tool of String Slicing
Next, let's introduce another main charactersplitA filter. 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 specified delimiter.
Imagine you have a string of comma-separated keywords: "SEO, content marketing, website optimization". If you want to display them as individual clickable tags, thensplitThe filter is the tool you need.
splitThe usage of the filter is as follows:
{% set tagsString = "SEO,内容营销,网站优化" %}
{% set tagsArray = tagsString|split:"," %}
{# 此时 tagsArray 就是一个包含三个元素的数组:["SEO", "内容营销", "网站优化"] #}
There are a few things to note:
- separator:
splitThe filter needs a string as a delimiter. In the above example, we used a comma,. - The delimiter does not existIf the original string does not contain the specified delimiter,
splitthe filter will return an array containing the original string as the only element. - empty delimiterIf the delimiter is an empty string,
"",splitThe filter splits each character of the string into an element of the array.
Core Practice:{% set %}withsplitThe perfect combination of filters
Now, let's take{% set %}andsplitCombine the filters to create a more practical scenario: Suppose your article detail page has aarchive.KeywordsField, its content is similar to
{# 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 %}Retrieved the original keyword string. The next critical step is{% set keywordList = rawKeywords|split:"," %}it completed the string splitting, and the split string array was assigned tokeywordListthis new variable.
Later, we go through one{% for %}Loop throughkeywordListEach keyword in the array. Inside the loop, in order to provide a better user experience and SEO friendliness, we cleverly combined withtrimFilter to remove any leading and trailing spaces from keywords as wellurlencodeFilter 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 the product model has a field that 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 background, 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 sliced and displayed in an album in a loop.
Summary
AnQiCMS's powerful template engine provides great flexibility, and{% set %}with the tag andsplitThe combination of filters is one of the keys to unlocking these potential.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 implementing other personalized content layouts, you will be able to do so with ease.Master these fundamental and powerful skills to better utilize AnQiCMS for managing and presenting your website content.
Frequently Asked Questions (FAQ)
Q1: IfsplitWhat will happen if the delimiter specified by the filter does not exist in the string?
A1: If the specified delimiter is not present 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 will still be treated as one element, you can use{% if variable %}to check if the array is empty, thus avoiding unnecessary output.
Q2:splitHow do I handle array elements after filter cutting if they themselves contain spaces?
A2: OnsplitAfter filtering the string, if there are spaces before and after the delimiter in the original string (for example"SEO , 内容营销"), the cut elements may also contain these spaces ("SEO "and" 内容营销")。In order to get clean elements, you can use a filter while traversing the array. For example:trimFilter to remove leading and trailing spaces. For example:{{ keyword|trim }}.
Q3:splitCan the filter handle non-string types of data (such as numbers)?
A3:splitThe filter is designed to process strings. If you try to apply it to non-string data types (such as a number), it will typically try to convert the data to a string first, then cut it.However, this implicit conversion may not meet your expectations, so it is recommended to usesplitBefore the filter, make sure your input data is already of string type. If you need to operate on numeric arrays, you may need to consider other methods or preprocess the data on the backend.