How to extract elements within a specified range from an array or string in Anqi CMS template?

Calendar 👁️ 61

In AnQiCMS template development, we often need to finely control the displayed content, such as extracting part of the text from a long string or displaying only the first few elements from a list. Fortunately, the class Django template engine adopted by AnQiCMS provides a very practical tool -sliceSlice filter, which can help us easily achieve these requirements.

sliceThe filter is a very flexible feature, it is not only suitable for strings (text), but also for array (list) data.Its core function is to extract a portion of the original data based on the specified range.This is very useful for controlling the length of page content, filtering specific data segments, and other scenarios.

sliceBasic usage of the filter.

sliceThe syntax of using filters is very intuitive:{{ 变量 | slice:"起始索引:结束索引" }}.

The "start index" and "end index" here determine the range of the slice, and the following points need to be noted:

  1. The index starts from 0Like most programming languages, the index in AnQiCMS templates also starts from 0. Therefore, the index of the first element or character is 0.
  2. The start index includes, the end index does not include:起始索引The specified position is the starting point of the截取范围的起点(包含在结果中),而结束索引The specified position is the end point of the截取范围的终点(不包含在结果中)。
  3. The index can be omitted:
    • If omitted起始索引for exampleslice:":5"Then it starts cutting from the beginning of the data (index 0).
    • If omitted结束索引for exampleslice:"5:"Then it starts cutting from起始索引Cutting to the end of the data at the specified position.
    • If both are omitted (for exampleslice:":"),will return the entire data (usually used for copying data).
  4. Negative index: Negative indices represent counting from the end of the data. For example,-1represents the last element/character,-2representing the second to last, and so on.
    • slice:"-3:"representing the last 3 elements/characters.
    • slice:":-2"representing all content except the last 2 elements/characters.

Actual application example

Next, let's understand how to use the AnQiCMS template through specific examplesslicefilter.

1. Extract the specified range of the string

Suppose you have a custom fieldarchive.DescriptionStored the article summary, you want to display only the first 50 characters on the list page, and the full summary on the detail page.

{# 假设 archive.Description 的值是 "AnQiCMS让网站运营更高效、可定制、易扩展,是中小企业和内容运营团队的首选工具。" #}

{# 显示前10个字符 #}
<p>简介(前10字):{{ archive.Description | slice:":10" }}</p>
{# 结果: 简介(前10字):AnQiCMS让网站运 #}

{# 从第5个字符开始,截取到末尾 #}
<p>简介(从第5字开始):{{ archive.Description | slice:"4:" }}</p>
{# 结果: 简介(从第5字开始):MS让网站运营更高效、可定制、易扩展,是中小企业和内容运营团队的首选工具。 #}

{# 截取第6到第15个字符 #}
<p>简介(第6到15字):{{ archive.Description | slice:"5:15" }}</p>
{# 结果: 简介(第6到15字):让网站运营更 #}

{# 截取最后8个字符 #}
<p>简介(最后8字):{{ archive.Description | slice:"-8:" }}</p>
{# 结果: 简介(最后8字):团队的首选工具。 #}

{# 截取除了最后5个字符之外的所有内容 #}
<p>简介(除了最后5字):{{ archive.Description | slice:":-5" }}</p>
{# 结果: 简介(除了最后5字):AnQiCMS让网站运营更高效、可定制、易扩展,是中小企业和内容运营团队的 #}

2. Extract the specified range from the array (list)

In AnQiCMS template,archiveList/tagList/categoryListThe tag usually returns an array containing multiple items. We can usesliceto control the number of entries displayed

Assuming you pass througharchiveListGot a list of articlesarchives,You only want to display the first three articles.

{% archiveList archives with type="list" limit="10" %}
    <div class="article-list-section">
        <h3>最新文章</h3>
        <ul>
            {% for item in archives | slice:":3" %} {# 只循环前3篇文章 #}
            <li>
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                <p>{{ item.Description | slice:":30" }}...</p> {# 再次对简介进行截取 #}
            </li>
            {% endfor %}
        </ul>
    </div>
{% endarchiveList %}

{# 进一步的例子:获取列表中从第二篇开始的四篇文章 #}
{% archiveList allArchives with type="list" limit="10" %}
    <div class="featured-articles">
        <h3>推荐文章(中间4篇)</h3>
        <ul>
            {% for item in allArchives | slice:"1:5" %} {# 索引1是第二篇,截取到索引5(不含),即第2、3、4、5篇 #}
            <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
            {% endfor %}
        </ul>
    </div>
{% endarchiveList %}

3. Combine other filters: Convert string to array and then truncate.

Sometimes, the data stored in a database may be a string separated by commas or other symbols, such as a list of keywords for an article: 'SEO optimization, content marketing, website security'.If you want to display only the first two keywords, you need to convert the string to an array first, and then perform slicing operations.

{# 假设 archive.Keywords 的值是 "SEO优化,内容营销,网站安全,模板定制" #}

{% set keywordArray = archive.Keywords | split:"," %} {# 使用 split 过滤器将字符串按逗号分隔成数组 #}
{% set firstTwoKeywords = keywordArray | slice:":2" %} {# 截取数组中的前两个元素 #}

<p>文章关键词:{{ firstTwoKeywords | join:" / " }}</p>
{# 结果: 文章关键词:SEO优化 / 内容营销 #}

{# 或者你可以将这些操作串联起来 #}
<p>文章关键词(简化版):{{ archive.Keywords | split:"," | slice:":2" | join:" | " }}</p>
{# 结果: 文章关键词(简化版):SEO优化 | 内容营销 #}

温馨提示

  • Index out of bounds handlingIn AnQiCMS template,sliceThe filter has good tolerance for index out of bounds. If the start or end index you specify is beyond the actual length of the data, it will not throw an error but will return the content within the maximum valid range it can handle.For example, an array with only 5 elements, you execute|slice:":10"It will still return all 5 elements. If you request a non-existent range (such asslice:"10:12"), it will return an empty array or an empty string.
  • Temporary variable enhances readabilityWhen your template logic becomes complex, or you need to operate on the same slice result multiple times, use{% set 变量名 = ... %}This way of storing the slice result in a temporary variable can greatly improve the readability and maintainability of the template code.
  • Data type matches:sliceThe filter works for strings and arrays, but make sure your data type is one of them. For numbers, booleans, etc.,sliceit may not produce the expected effect.

By mastering the use ofsliceFilter, you can control the display of AnQiCMS website content more flexibly, making your template more powerful and dynamic.Why not try more in your project, and you will find its convenience.


Frequently Asked Questions (FAQ)

Q1: In AnQiCMS template, if I try to slice a string or array but the specified index exceeds its actual length, what will happen? Will it throw an error?

A1:No error. The template engine of AnQiCMS is forsliceThe index out of bounds in operation has a good error tolerance. If the range you specify exceeds the actual length, it will intelligently return the content within the maximum valid range it can handle.For example, if you have an array containing 5 elements, and you try to use|slice:":10"Slice the first 10, it will still return all 5 elements. If you specify a range that is completely beyond the data itself, such as an array of 5 elements you execute `|slice:“10

Related articles

How does the `join` filter behave when processing non-array objects (such as strings)?

In Anqi CMS template development, the `join` filter is a very practical tool, mainly used to concatenate elements of an iterable object (such as an array or list) into a single string with a specified separator.However, when we apply the `join` filter to non-array objects, especially strings, its behavior may be different from what we initially imagine, but understanding its working principle can help us use it more flexibly.### The basic functionality of `join` filter review First, let's review the most common uses of the `join` filter

2025-11-08

How to concatenate array elements in an Anqi CMS template with a custom character into a string?

In AnQi CMS template design, we often encounter situations where we need to display list-type data, such as multiple tags of an article, multiple image links on a product details page, or multiple options stored in a custom field.Directly outputting these array-shaped data to the page will often show a similar format like `["Label one", "Label two", "Label three"]`, which clearly does not meet the aesthetic and reading habits of users.At this point, we need to find a method to separate each element of the array with a custom character (such as a comma

2025-11-08

How does the `split` filter split a string into an array of characters?

When using AnQiCMS for website content creation and template development, string processing is a common requirement.Sometimes, we need to split a complete string into smaller parts, such as breaking it down into an array of characters.This article will delve into the powerful `split` filter feature in AnQiCMS and provide practical examples.

2025-11-08

How to split a string into an array using a specific delimiter in Anqi CMS template?

In the template development of AnQi CMS, we often encounter situations where we need to process specific strings.For example, a keyword of an article may be stored as a comma-separated string, and we want to display them as separate tags on the front end.At this point, splitting a string into an array with a specific delimiter becomes the key step in handling such issues.The AnQi CMS template engine supports syntax similar to Django, and it provides a rich set of filters (filters) to help us process data.

2025-11-08

How does the `slice` filter implement the function of extracting elements from the end of an array?

In AnQiCMS template development, the `slice` filter is a very practical tool that allows us to flexibly extract a part of the string or array content.But do you know? It can also realize a particularly clever function - to extract elements from the end of an array or list, which is very convenient when it comes to displaying the latest data or removing old data.Today, let's delve into how the `slice` filter achieves this functionality through negative indices.Understanding the basic usage of the `slice` filter As the name implies

2025-11-08

How to determine whether an array or string in an Anqicms template contains a specific keyword?

In AnQi CMS template development, we often need to dynamically display information based on specific attributes or keywords of the content.For example, determine whether an article title contains a certain product name, or check whether a document's tag list contains a hot keyword.This can not only make the website content more targeted, but also improve user experience and SEO effect.The AnQi CMS template engine provides powerful and flexible features to meet these needs.Among them, it is easy to determine whether an array or string contains a specific keyword by using the built-in `contain` filter.

2025-11-08

Can the `contain` filter be used to check if a Map (key-value pair) contains a specific key?

AnQiCMS with its efficient and customizable features brings many conveniences to content management.In the daily operation of websites, we often need to dynamically adjust the page content in templates based on the existence of data.Among them, it is a common requirement to judge whether a specific key exists in the data of key-value pair (Map) type.Today, let's delve into whether and how the `contain` filter in AnQiCMS templates can be used to check for the existence of keys in a Map.

2025-11-08

How to calculate the number of times a keyword appears in a string or array in the Anqi CMS template?

In content operation, precisely mastering the use of keywords on the page plays a crucial role in SEO strategy, content quality assessment, and user experience optimization.AnQiCMS (AnQiCMS) is a flexible and efficient content management system with a powerful template engine built-in with many practical features, including a filter that can help us easily calculate the number of times keywords appear.Next, we will introduce how to use these features to count the frequency of keywords in the Anqi CMS template.### Deeply understand `count`

2025-11-08