How to use the `slice` filter to extract a specified range of characters or elements from a string or array?

Calendar 👁️ 64

In the process of making AnQiCMS templates, it is an indispensable skill to flexibly handle strings and arrays. Whether it is to display the abstract of an article or to extract part of the elements from a list,sliceFilters can provide powerful and convenient assistance. It allows you to extract specific ranges of characters from strings or select elements from arrays at specified positions, making content display more accurate and diverse.

sliceWhat is a filter?

In simple terms,sliceThe filter acts like a precise pair of scissors, able to cut out the part you need from a piece of text (string) or a set of data (array, list) according to the specified start and end positions.Its core function is to "cut" or "slice".

sliceHow does the filter work?

sliceThe filter usesobj|slice:"from:to"syntax format.

  • objrepresents the string or array variable you want to operate on.
  • fromIs the starting index, indicating where to start cutting. Remember that in the AnQiCMS template system, the index usually starts from0start counting.
  • toIs the end index, indicating where to stop cutting. It should be noted that,toThe element pointed toWill not be includedIn the cutting result.

You can also omitfromorto:

  • If omittedfrom(For example)obj|slice:":to") indicates from the beginning (index 0) up totothe specified position.
  • If omittedto(For example)obj|slice:"from:") indicates fromfromthe specified position up to the end.
  • You can also use negative indices, which are very convenient in some cases. Negative indices represent counting from the end of a string or an array. For example,-1represents the last element,-2representing the second-to-last element.

Where can it be used?

sliceFilters are widely used in practical content operations:

  • Extracting the abstract or title of an article: When the article title is too long or needs to display a content summary, it can easily extract the first N characters.
  • Handle navigation or tag listsIf the number of navigation menus or tags is too many, only a part of the most commonly used or most important ones can be displayed.
  • URL path segment extractionParsing a specific part of a particular URL.
  • Display some images from the image collectionFor example, only display the first three images from the product image collection.
  • Generate a brief description text: Extract a section from the longer description as a preview.

Practice:sliceExample of filter usage

We understand through some specific examplessliceThe usage of filters. Suppose we have a string"欢迎使用安企CMS,轻松管理您的内容!"and an array["苹果", "香蕉", "橘子", "葡萄", "西瓜", "芒果"].

1. Extracting strings

Basic Extraction (fromfromtoto):

{# 截取字符串的第 1 到第 5 个字符(索引从0开始,所以是索引0到4) #}
{{ "欢迎使用安企CMS,轻松管理您的内容!"|slice:"0:5" }}
{# 显示结果:欢迎使用安企 #}

{# 截取字符串的第 5 到第 9 个字符(索引4到8) #}
{{ "欢迎使用安企CMS,轻松管理您的内容!"|slice:"4:9" }}
{# 显示结果:安企CMS, #}

Extract from the beginning to a specified position:

{# 截取前 7 个字符(索引0到6) #}
{{ "欢迎使用安企CMS,轻松管理您的内容!"|slice:":7" }}
{# 显示结果:欢迎使用安企CMS #}

Extract from a specified position to the end:

{# 从第 11 个字符(索引10)开始截取到末尾 #}
{{ "欢迎使用安企CMS,轻松管理您的内容!"|slice:"10:" }}
{# 显示结果:轻松管理您的内容! #}

Using negative indices (counting from the end):

{# 截取最后 5 个字符 #}
{{ "欢迎使用安企CMS,轻松管理您的内容!"|slice:"-5:" }}
{# 显示结果:您的内容! #}

{# 截取除了最后 8 个字符之外的所有内容 #}
{{ "欢迎使用安企CMS,轻松管理您的内容!"|slice:":-8" }}
{# 显示结果:欢迎使用安企CMS,轻松 #}

Handling Chinese characters:AnQiCMS'sliceThe filter can correctly handle UTF-8 encoded Chinese characters, where a Chinese character is treated as a unit rather than multiple bytes.

{{ "你好世界"|slice:"1:3" }}
{# 显示结果:好世 #}

2. Slice an array or list

When we need to process an array, we usually combinesplitThe filter converts a string to an array or directly operates on an existing array variable.

To extract a portion of the array elements:

{% set fruits = ["苹果", "香蕉", "橘子", "葡萄", "西瓜", "芒果"] %}

{# 截取数组中索引 1 到 4 的元素(香蕉、橘子、葡萄) #}
{{ fruits|slice:"1:4"|join:"-" }}
{# 显示结果:香蕉-橘子-葡萄 #}

{# 截取数组中的前 3 个元素 #}
{{ fruits|slice:":3"|join:", " }}
{# 显示结果:苹果, 香蕉, 橘子 #}

{# 截取数组中的最后 2 个元素 #}
{{ fruits|slice:"-2:"|join:" 和 " }}
{# 显示结果:西瓜 和 芒果 #}

Some tips

  1. Index from0Start: It is a common convention in programming languages, getting accustomed to it can help avoid many mistakes.
  2. toIndex does not include:slice:"from:to"The actual extracted isfromtoto-1within the range of elements.
  3. Out of boundary handlingIf:fromortoThe index exceeds the actual length of the string or array,sliceThe filter usually does not report an error but intelligently returns the available part or an empty value, which is very friendly during template rendering.
  4. Combine with other filters: As shown in the above example,sliceoften withsplitSplit strings into arrays andjoinUse the filter to concatenate arrays into strings, to achieve more complex text processing logic.

Through proficiencysliceFilter, you will be able to display your content more efficiently and flexibly in AnQiCMS, enhancing the user experience of the website.


Frequently Asked Questions (FAQ)

1.sliceFilters andtruncatecharsWhat are the differences between filters? sliceThe filter is purely for slicing strings or array elements by index, it will not automatically add an ellipsis (such as...), nor will it consider the integrity of the word.truncatecharsThe filter is mainly used for strings, it will automatically add an ellipsis after truncating to a specified length, and will try to avoid breaking a word in the middle to maintain readability. If you need to precisely control the truncation range and do not want to automatically add an ellipsis, please usesliceIf you are looking to generate an ellipsis summary,truncatecharsortruncatewordsWould be a better choice.

Related articles

What are the differences between `trim`, `trimLeft`, and `trimRight` filters in removing whitespace or specific characters from a string?

In website content management, we often encounter situations where we need to clean and format strings, such as removing extra spaces at the beginning and end of user input text, or standardizing data with specific prefixes or suffixes.AnQiCMS provides a series of powerful template filters to simplify these operations, among which `trim`, `trimLeft`, and `trimRight` are powerful tools for handling string leading and trailing characters.They have similar functions but have different scopes.

2025-11-08

How to limit the display length of the link text when converting URLs with the `urlizetrunc` filter?

In AnQiCMS (AnQiCMS) content operation practice, we often encounter some details that require fine-grained processing, one of which is how to elegantly display the super-long URL on the page.When a text contains a long URL, it may destroy the page layout and affect the overall aesthetics and the reading experience of the user.Fortunately, Anqi CMS provides the `urlizetrunc` filter, which can help us easily solve this problem, allowing URLs to be converted into clickable links while still controlling their display length

2025-11-08

How does AnQiCMS automatically identify URL links in text and convert them into clickable `<a>` tags?

During content creation and publication, we often encounter situations where we need to cite external sources or share relevant links.If these URLs are in plain text form, users not only need to manually copy and paste them, but it will also affect the reading experience and the professionalism of the website.Anqi CMS knows this pain point, and therefore integrated the intelligent URL automatic recognition and conversion function from the beginning of the system design, making your content publishing more efficient and convenient, and improving the user experience accordingly.### Intelligent recognition, automatic conversion: Say goodbye to manual operation AnQi CMS through its powerful template engine

2025-11-08

What is the difference between the `urlencode` and `iriencode` filters in URL escaping?

In the daily content operation and website development of Anqi CMS, we often need to handle URL links to ensure that they are both secure and effective, and can be correctly parsed by browsers and search engines.This is an indispensable part of URL escaping (also known as encoding).Our Anqi CMS provides us with two very practical filters: `urlencode` and `iriencode`, both of which can help us with URL escaping, but their purposes and processing methods are different in actual application.###

2025-11-08

The `stringformat` filter provides which advanced string formatting options (such as number precision, alignment style)?

In the powerful template system of AnQi CMS, we often need to present dynamic data on the website, and the way data is displayed directly affects user experience and the efficiency of information communication.To present numbers, text, and other content in a more professional and clear manner, AnQi CMS provides the `stringformat` filter, which is a multifunctional formatting tool that helps us finely control the display details of content.The `stringformat` filter plays a role in AnQi CMS similar to the `fmt` in Go language

2025-11-08

How to repeat a string a specified number of times, for example, to display a welcome message repeatedly?

In website content operations, we often encounter situations where we need to repeat certain information, such as repeating copyright information in the footer, playing a greeting phrase in the welcome area repeatedly, or adding visual separators between list items.Copying and pasting manually is not only inefficient but also very麻烦 when it needs to be modified.Luckyly, AnQiCMS's powerful template engine provides a simple and efficient way to solve this problem, one very practical feature is the `repeat` filter.###

2025-11-08

What risks should be noted when using the `safe` filter to prevent XSS attacks in AnQiCMS templates?

AanQi CMS has always paid great attention to security from the very beginning, which is fully reflected in its concise and efficient Go language architecture, aiming to provide users with a secure and stable content management environment.In the daily content publishing and template creation, we often come across various template tags and filters.Among them, the `safe` filter is a powerful tool but also one that requires our special vigilance.It allows us to output raw HTML content in the template, but it is precisely this 'freedom' that hides some risks that should not be overlooked, especially in preventing cross-site scripting (XSS) attacks.

2025-11-08

How to use the `escapejs` filter to safely embed template variables into JavaScript code?

In the daily use of AnQi CMS, we often need to display the content of the background management, such as article titles, user comments, or other dynamic data, on the front-end page.This content is not just plain text, it also needs to be used in JavaScript code, such as variable values, function parameters, or dynamically generated HTML fragments.However, embedding template variables directly into JavaScript code, if not handled properly, may introduce a significant security vulnerability - cross-site scripting (XSS)

2025-11-08