How to get the first or last element of an array split by the `split` filter?

Calendar 👁️ 73

When managing content in AnQi CMS, we often encounter the need to process some text information stored in a specific format.For example, the keywords of an article are usually stored in a field in the form of a comma-separated string, such as “AnQi CMS, content operation, template creation”.When we want to highlight the most important keyword on the website front-end, such as in an article list or detail page, or to get the last keyword as a hint, we need to split these strings and extract the specific elements.

幸运的是,the AnQi CMS built-in template engine provides powerful filter functions, which can easily meet such needs. Among them,splitThe filter can split a string into a collection of data according to a specified delimiter, which in programming is usually called an array or slice, andfirstandlastThe filter can help us quickly obtain the first or last element of this data set.

Core function:splitFilter

First, we need to convert the original string content into a manipulable dataset. At this point,splitThe filter comes into play. Its function is to split a long string into a collection of short strings based on the delimiter you provide.

Assuming we have a variablearchive.KeywordsIts value is"安企CMS,内容运营,模板制作"And we hope to split by comma,Split it. We can first usesetlabels to declare a temporary variable, andsplitstore the result of the filter for later use:

{% set keyword_string = archive.Keywords %}
{% set keyword_array = keyword_string|split:"," %}

Now,keyword_arraythis temporary variable becomes a container that includes["安企CMS", "内容运营", "模板制作"]such a data set.

Get the first element: clever use.firstFilter

When we got the cut data set.keyword_arrayAfter, it is very simple to get the first element. Anqi CMS template engine provides an intuitivefirstA filter. This filter can be directly applied to a dataset, returning its first member.

Carrying on from the previous example, if we want to display the article's "main keyword", which is the first element in the data set, we can write it like this:

主要关键词:{{ keyword_array|first }}

After running, the page will display: "Main keywords: AnQi CMS."

Get the last element: Use flexibly.lastFilter

withfirstThe filter is analogous, if we need to get the last element of the data set, we can uselastThe filter is also simple and clear, able to directly return the last member of the data set.

If we want to display the 'other keywords' of the article, and assume that the last keyword can represent some secondary information, we can get it in this way:

其他关键词:{{ keyword_array|last }}

After running, the page will display: "Other keywords: template creation."

Comprehensive example: application in practice.

Imagine on your article detail page, you want to display several main keywords below the article title, and randomly select a tag as a recommendation in the footer "related tags" section.

{% set keywords_str = archive.Keywords %} {# 假设 archive.Keywords 为 "SEO,安企CMS,建站,网站优化" #}
{% set keyword_list = keywords_str|split:"," %}

<div class="article-meta">
    <h1>{{ archive.Title }}</h1>
    <p>主要聚焦:<span class="highlight-keyword">{{ keyword_list|first }}</span></p>
    {# 其他元信息如发布时间、作者等 #}
</div>

{# 页面其他内容 #}

<div class="footer-related-tags">
    <h3>猜你喜欢</h3>
    <p>探索更多关于 <a href="/tags/{{ keyword_list|last }}">{{ keyword_list|last }}</a> 的内容。</p>
</div>

By such a combination application, we can not only flexibly structure the string data, but also accurately extract and display the key information according to different display requirements, making the template content more dynamic and rich.

Frequently Asked Questions (FAQ)

  1. If my string is empty, or the delimiter does not exist in the string,splitHow will the filter perform?firstorlastcan it still work?

    • when the string is empty (for example,""),splitThe filter will return an array containing an empty string, i.e.[""]. At this point,|firstand|lastwill return an empty string"".
    • If the delimiter does not exist in the string (for example"安企CMS"Use,delimiter),splitThe filter will return an array containing the original string itself, that is["安企CMS"]. At this point,|firstand|lastwill all return the original string"安企CMS".
    • Therefore, even in these special cases,firstandlastThe filter can still provide predictable results without causing program errors.
  2. firstandlastThe filter is not only used to processsplitthe array after, can it also be used for other data types?

    • Yes,firstandlastThe filter can also be used to processsplitAfter an array (or slice), it can also be directly applied to a string. When applied to a string,firstit returns the first character of the string,lastwhile it returns the last character. For example,"你好世界"|firstwill return"你"while"你好世界"|lastwill return"界"This makes them very flexible in handling various types of data.
  3. How do I get a specific element from the middle of an array after slicing, rather than the first or last one?

    • When you need to access a specific element in an array, you can use the index directly. In the Anqi CMS template engine, array indices start from0Start. For example, to get the second element, you can write like this:{{ keyword_array[1] }}. If you need a more complex cut, such as getting from the Nth to the Mth element,sliceThe filter would be a better choice, usually combinedfirstorforFor example, to use it cyclically{{ keyword_array|slice:"1:3" }}It will get a new array composed of elements from index 1 to index 2 (i.e., the 2nd and 3rd elements).

Related articles

Can the `split` filter use tab or newline characters as delimiters, in addition to commas and spaces?

When using AnQi CMS for content management and template development, we often need to handle strings and split them into smaller data segments according to specific rules.The `split` filter is undoubtedly an important tool to achieve this goal.However, many friends may habitually think that `split` can only handle common separators such as commas, spaces, etc.Can tab characters and newline characters also be valid delimiters for the `split` filter?Today, let's delve into this topic in depth.

2025-11-08

Do `split` filters have special considerations when processing data for different sites in the AnQiCMS multi-site environment?

Are there special considerations when the `split` filter processes data for different sites in the AnQiCMS multi-site environment?Under the multi-site management capability of AnQiCMS, we often need to display content and handle data between different sites.The `split` filter is a basic and powerful string processing tool in the template engine and is naturally used frequently.

2025-11-08

Does the `split` filter affect the performance of template rendering when cutting large strings or complex data?

In website operations and template development, we often make use of the various powerful and flexible template filters provided by AnQiCMS to process data, among which the `split` filter is popular for its ability to easily split strings into arrays.However, when dealing with large strings or complex data structures, some users may wonder whether the `split` filter will affect the performance of template rendering.To deeply understand this problem, we first need to talk about the core technology stack of AnQiCMS.

2025-11-08

How to combine the `split` filter with the `if` logical judgment tag to perform different operations based on the cutting results?

In website content management, we often encounter a situation where a field stores a string of data separated by a specific symbol, and we need to perform different operations based on the results after the data is split.For example, an article tag field may store “SEO, operation, content marketing”, or a product attribute field may store “Color: red, size: L”.The AnQi CMS template engine provides powerful `split` filters and `if` logical judgment tags, which can be used together to achieve this requirement in a very flexible manner.

2025-11-08

How would the `split` filter handle consecutive delimiters in a string, for example `"a,,b"` using a comma as the delimiter?

AnQi CMS has always been favored by users for its flexibility and powerful functions in content display and management.When dealing with dynamic content, we often encounter the need to split strings and extract information.At this time, the `split` filter in the template is particularly practical.It can help us split a continuous string of text data into independent segments according to the specified delimiter, so that it can be displayed and processed more finely on the page.

2025-11-08

Does the `split` filter support more complex delimiter patterns, such as matching specific prefix and suffix characters?

In AnQiCMS template development, the `split` filter is a very useful tool that can help us split strings into arrays according to specified delimiters, which is especially convenient for handling data connected by specific characters.However, when it comes to more complex delimiter patterns, such as when it is necessary to match specific prefixes and suffixes of characters, the capabilities of the `split` filter are worth exploring in depth.

2025-11-08

How to pass the array elements split by the `split` filter as parameters to other template tags or filters?

The template system of AnQiCMS (AnQiCMS) is favored by content operators for its powerful flexibility and ease of use.Among them, the `split` filter is a very practical feature that can help us split a string into an array (or called a slice in Go language) according to the specified delimiter.However, when we want to pass a specific part of this array as a parameter to other template tags or filters, we may feel a bit confused.Don't worry, this article will discuss in detail several efficient and commonly used methods to solve this problem.--- ###

2025-11-08

The `split` filter splits an array, if you need to format each element (such as `upper` or `lower`), how to implement chaining?

In Anqi CMS template development, flexibly using various filters (Filters) can greatly facilitate our formatting of content.When we encounter the need to split a string into multiple parts by a specific delimiter, and then to further format each part (that is, each element of the array) for example, to convert them all to uppercase or lowercase, we cannot perform the chaining operation as simply as we do with a single string.The AnQi CMS template engine supports syntax similar to Django, it provides a powerful `split` filter

2025-11-08