During the template development process of Anqi CMS,splitA filter is a very practical tool that allows us to easily split strings into arrays according to a specified delimiter. This is particularly important in various scenarios such as handling tag lists, keyword strings, and so on. However, when usingsplitWhen filtering, some users may want to directly limit the maximum length of the array generated after cutting.

Then, the in-built of Anqi CMS is.splitDoes the filter provide such a parameter or method? After a deep understanding of the system's functions, we found thatsplitThe design goal of the filter itself is purely to complete the string splitting task, it does notinclude built-in parameters that directly limit the maximum length of the output array. That is to say, when you usesplitWhen cutting a string, it will try its best to cut out all substrings that meet the delimiter conditions, generating an array containing all the results.

AlthoughsplitThe filter itself does not have this feature, but it does not mean we cannot limit the length of the array. The template engine of Anqi CMS provides other flexible and powerful filters and logic tags that can be used withsplitUse filters in combination to easily achieve the desired effect. Next, we will explore several effective strategies for limiting the length of arrays.

splitReview of the basics of filters

Let's quickly review firstsplitThe basic usage of the filter.The main function is to split a string into an array of strings based on the delimiter you provide."SEO, 关键词优化, 网站推广"and hope to split it into a list of separate keywords, you can use it like thissplit:

{% set keywordString = "SEO, 关键词优化, 网站推广, 内容营销, 品牌建设, 用户体验" %}
{% set keywordsArray = keywordString|split:", " %}
{{ keywordsArray|stringformat:"%#v" }}

This code will generate a Go language string slice (slice) containing all the split results, outputting something like[]string{"SEO", "关键词优化", "网站推广", "内容营销", "品牌建设", "用户体验"}You can see,splitFocused on complete splitting, will not truncate by itself.

Implement a strategy to limit the length of the array.

SincesplitThere is no direct length limitation feature, we can achieve this by combining other filters and template logic.

1. Smart usesliceFilter to slice array

sliceThe filter is a powerful tool for processing array (or string) slicing. It can extract a portion of data based on the specified start and end indices. When used withsplitThis is the ideal solution to limit the length of the array when using filters together.

sliceThe format for using filters is usually{{ obj|slice:"from:to" }}where,fromis the start index (inclusive),toThe end index (not included). If we want to limit the maximum length of the array,Nwe just need to slice the array from the beginning to the Nth element.

Assuming we want to limit the length of the above keywords array to a maximum of 3, we can do it like this:

{% set keywordString = "SEO, 关键词优化, 网站推广, 内容营销, 品牌建设, 用户体验" %}
{% set keywordsArray = keywordString|split:", " %}
{% set limitedKeywords = keywordsArray|slice:":3" %} {# 截取数组的前3个元素 #}

{# 遍历并显示限制后的关键词 #}
{% for item in limitedKeywords %}
    <span>{{ item }}</span>
{% endfor %}

In this way, no matter how many keywords are cut from the original string,limitedKeywordsThe array will have at most 3 elements.sliceThe filter here plays the role of a 'physical' truncation of the array, very efficient and intuitive.

2. CombineforLoop withforloop.CounterIterative control

If your requirement is not to actually 'truncate' the array itself, but merely to display or process only the first N elements while traversing the array, then combiningforloop andforloop.CounterVariables would be a more elegant choice.

In the Anqi CMS.forin the loop,forloop.CounterIt will return the current loop count (starting from 1).We can take advantage of this, setting a condition within the loop to stop the subsequent display or processing once we reach the maximum length we have set.

Continuing with the example of keywords, we hope to display only the first 4 keywords on the page:

{% set keywordString = "SEO, 关键词优化, 网站推广, 内容营销, 品牌建设, 用户体验" %}
{% set keywordsArray = keywordString|split:", " %}

{# 遍历关键词,并限制显示数量 #}
{% for item in keywordsArray %}
    {% if forloop.Counter <= 4 %} {# 只显示前4个 #}
        <span>{{ item }}</span>
    {% endif %}
{% endfor %}

The advantage of this method is that the originalkeywordsArrayIt is still complete, and if you need all the keywords elsewhere in the template, they are still available. This approach is more focused ondisplay logic limitationsInstead of modifying the data structure.

3. UselengthFilter is related toifto make a judgment

In some scenarios, you may need to judge according tosplitThe actual length of the array determines the different display logic, rather than simply truncating. At this time,lengthThe filter comes into play.lengthThe filter can obtain the length of a string, array, or key-value pair.

For example, if the number of keywords after cutting exceeds 5, we may wish to add a "More..." link at the end; if it is less than 5, it is displayed normally.

{% set keywordString = "SEO, 关键词优化, 网站推广, 内容营销, 品牌建设, 用户体验" %}
{% set keywordsArray = keywordString|split:", " %}
{% set maxDisplay = 5 %}

{% for item in keywordsArray %}
    {% if forloop.Counter <= maxDisplay %}
        <span>{{ item }}</span>
    {% endif %}
{% endfor %}

{# 判断是否需要显示“更多”链接 #}
{% if keywordsArray|length > maxDisplay %}
    <a href="/more-keywords">更多...</a>
{% endif %}

This method provides you with greater flexibility, allowing you to customize different template behaviors according to the actual size of the array.

Recommended application scenarios

In the actual content operation and template development, the choice of method depends on your specific needs:

  • If the goal is to generate a 'physically' shorter array and use it for further data processing or pass it to other componentsso thatsplitCombinesliceFilterIt is the most direct and efficient way. It creates a new, shorter array, reducing unnecessary memory usage and loop iterations.
  • If the goal is only to display or render the first N elements of the array on the page, while the original complete array may still be needed elsewherethenforUsing in a loopforloop.CounterPerform conditional judgmentIt is a more flexible choice. It does not modify the original data structure.
  • If you need to trigger different layouts or prompts based on the actual length of the arraythen uselengthFilter is related toifconditionis ideal.

The template engine of AnQi CMS is although insplitThere is no direct length limit function on the filter, but with the rich filters and logical tags provided, we can completely combine solutions to meet complex needs.Understanding the characteristics of these tools and applying them flexibly in real scenarios will greatly enhance your template development efficiency and the quality of content presentation.


Common Questions (FAQ)

1. If I only want to displaysplitWhich method is recommended for the first few elements cut out by the filter?

If you only need to display the first few elements of an array and do not mind creating a new truncated array to handle it, then it is recommended to usesplitCombineslicea filter. For example{{ (yourString|split:", ")|slice:":5" }}This method is concise and clear. If you need to traverse and display inforthe loopforloop.CounterIt is also recommended to perform conditional judgments, as it can avoid creating a new array, but it is limited to display-level restrictions.

Can I reassemble the array after the operation?splitinto a string?

Of course, the Anqi CMS template engine providesjoina filter that can reassemble array elements into a string using a specified delimiter. For example, if you have an array namedmyArrayThe array, to concatenate it with commas and spaces, you can write it like this:{{ myArray|join:", " }}. This is the opposite ofsplitfunction, usually used together to flexibly handle the conversion between strings and arrays.

3. If the delimiter I use does not exist in the string,splitwhat will the filter return?

WhensplitWhen the delimiter specified in the filter does not exist at all in the target string, it returns an array containing a single element, which is the original complete string itself. For example, "Hello World"|split:","Will return `[]string{"Hello World"}