How to use the `slice` filter to extract specific parts of parameters or paths from a long URL?

Calendar 👁️ 73

In the Anqi CMS template world, flexible data processing is the key to improving website user experience and SEO performance.Sometimes, we need to extract a specific part from a longer URL, such as path parameters, product ID, or just display a part of the URL to keep the page concise. At this point,sliceA filter is an extremely useful tool that can help us accurately extract any segment of a string or array.

UnderstandingsliceThe principle of the filter.

sliceThe filter allows us to extract a portion of content from a string or array based on specified start and end positions. Its basic syntax is{{ 对象|slice:"起始位置:结束位置" }}. The "object" can be any string variable or an array variable.

  • Starting position (from): Specify where to start cutting. If omitted, it defaults to the beginning (index 0). The index starts from 0.
  • End position (to): Specify where to cut off, but not including the element at that position. If omitted, it defaults to the end.
  • Colon (:):起始位置and结束位置must be separated by a colon.

Furthermore,sliceThe filter also supports negative indices, which makes it very convenient to count from the end of a string or array. For example,-1represents the first element from the end,-3this represents the third element from the end.

Practice Application: Extracting Parameters or Paths from Long URLs

Let's look at a few specific examples to see how we can utilizeslicefilters to process long URLs.

Example 1: Extract the specific path segment from the URL

Assuming the structure of our article detail page URL is as follows:/category/tech/detail/article-anqicms-tutorial.html. Now, we only want to display the "tech" category identifier or the "article-anqicms-tutorial" article alias on the page.

sliceThe filter itself directly acts on characters or array elements. For complex URLs, we usually need to usesplitThe filter splits the URL by the slash/Split into an array of path segments and then usesliceExtract the required part

{% set fullPath = archive.Link %} {# 假设archive.Link获取到的是 /category/tech/detail/article-anqicms-tutorial.html #}
{% set pathSegments = fullPath|split:"/" %} {# 结果类似 ["", "category", "tech", "detail", "article-anqicms-tutorial.html"] #}

{# 提取分类标识 "tech" (位于索引 2) #}
{% set categoryIdentifier = pathSegments|slice:"2:3"|join:"" %}
<div>当前文章分类标识:{{ categoryIdentifier }}</div> {# 输出:tech #}

{# 提取文章别名 "article-anqicms-tutorial.html" (位于数组末尾) #}
{% set articleSlug = pathSegments|slice:"-1:"|join:"" %}
<div>文章别名:{{ articleSlug }}</div> {# 输出:article-anqicms-tutorial.html #}

{# 如果我们只需要别名中的"article-anqicms-tutorial"部分,可以进一步处理 #}
{% set articleNameWithoutExtension = articleSlug|slice:":-5" %} {# 截取掉 .html (5个字符) #}
<div>文章名称:{{ articleNameWithoutExtension }}</div> {# 输出:article-anqicms-tutorial #}

here,join:""issliceConvert the single-element array returned to a string

Example two: Simplify the display of long URLs

Sometimes, for the neatness of the page layout, we may not want to display the full URL, but only show the core domain name plus an ellipsis and part of the path.

{% set fullUrl = "https://en.anqicms.com/docs/template/filters/slice-filter-usage.html?param1=value1&param2=value2" %}

{# 假设我们只想显示 "anqicms.com/.../slice-filter-usage.html" #}
{% set domainPart = fullUrl|split:"/"|slice:"2:3"|join:"" %} {# 提取 anqicms.com #}
{% set pathSuffix = fullUrl|split:"/"|slice:"-2:" %} {# 提取最后两个路径段,如 ["filters", "slice-filter-usage.html?param1=value1&param2=value2"] #}

<div>简化URL:{{ domainPart }}/.../{{ pathSuffix|join:"/" }}</div>
{# 输出:anqicms.com/.../filters/slice-filter-usage.html?param1=value1&param2=value2 #}

{# 如果需要更简洁,只保留文件名称 #}
{% set lastSegment = pathSuffix|slice:"-1:"|join:"" %} {# 再次截取最后一个 #}
{% set filenameOnly = lastSegment|split:"?"|slice:"0:1"|join:"" %} {# 去掉查询参数 #}

<div>更简洁URL:{{ domainPart }}/.../{{ filenameOnly }}</div>
{# 输出:anqicms.com/.../slice-filter-usage.html #}

Example three: Extracting a numeric ID from a custom field with an ID

Assuming you have customized a field in the background to store a mixed string containing product SKUs and IDs, for exampleproduct-SKU123-ID456. Now, you need to extract only the456This number ID.

{% set customFieldString = "product-SKU123-ID456" %}

{# 先按"-"分割 #}
{% set parts = customFieldString|split:"-" %} {# 结果类似 ["product", "SKU123", "ID456"] #}

{# 提取包含ID的部分 "ID456" (位于索引 2) #}
{% set idPart = parts|slice:"2:3"|join:"" %} {# 结果 "ID456" #}

{# 从 "ID456" 中提取数字部分 #}
{% set numericId = idPart|slice:"2:" %} {# 从索引 2 开始截取,即跳过 "ID" #}

<div>提取的数字ID:{{ numericId }}</div> {# 输出:456 #}

It is not difficult to find through these examples,slicethe filter meetssplit/joinCombined with other filters, it can bring out powerful string processing capabilities, helping us flexibly display and utilize information in the URL.

Use instructions when in use

  • The index starts from 0Remember that the first element index of a string or array is 0.
  • The end position does not include:slice:"from:to"It will capture fromfromFromto-1To the element.
  • The clever use of negative indices: For strings or arrays of undefined length, negative indices can be conveniently used to operate from the end.
  • Combined with other filters: When dealing with complex strings like URLs,splitandjoinfilters are oftensliceyour partner.
  • Testing is the key.Before applying in a production environment, be sure to develop

Related articles

Does the `slice` filter support negative indices to start cutting from the end?

In AnQi CMS template development, we often need to flexibly truncate and display strings or data lists, only showing a part of them.The `slice` filter is designed for this purpose, allowing us to precisely control the length of the content.And the answer to whether the `slice` filter supports negative indices, which is whether it can start cutting from the end, is affirmative, and this feature greatly enhances our flexibility and convenience when dealing with dynamic content templates.

2025-11-07

How to ensure the integrity of the sliced result when截取中文字符串 using the `slice` filter (to avoid half characters)?

In Anqi CMS template development, the `slice` filter is a commonly used tool for handling strings and arrays.It can help us conveniently extract a part of the content, whether it is several elements of a list or a specified segment of a long text.However, when it comes to cutting Chinese character strings, if you are not familiar with the underlying working principle, you may encounter a common and annoying problem: the cutting result appears as 'half a character' or garbage code.

2025-11-07

How to accurately slice an array in the AnQiCMS template?

During the template development process of AnQi CMS, we often need to flexibly handle the data displayed on the page, especially when the data is presented in the form of a list or sequence.Imagine that you are designing a product list page, where you need to select the top 5 most popular products from an array of dozens of products to display at the top of the page; or, you may need to truncate a long string from the content of an article detail page to use as a summary.

2025-11-07

How will the `length_is` filter handle non-string or numeric types when comparing lengths?

AnQiCMS provides rich template filters to help us flexibly handle and display data.Among them, the `length_is` filter is often used to determine whether the length of the variable meets expectations.However, during use, one may encounter a question: What will the system do if we pass non-string or non-numeric data to the `length_is` filter for length comparison?This is not just a technical detail, but also about how we avoid potential errors in template design and ensure the accuracy of data display.

2025-11-07

How to split a comma-separated keyword string configured in the AnQiCMS backend into an iterable keyword list?

In AnQiCMS (AnQiCMS) daily content operations, we often need to display related keywords on articles or product detail pages.These keywords not only help search engines understand the content of the page, but also guide users to discover more relevant information.In most cases, we will enter these keywords in a text box on the backend, separated by commas, for example: "website operation, SEO optimization, content marketing.

2025-11-07

What are the different splitting behaviors when the delimiter is empty or not present?

In AnQi CMS template development, the `split` filter is a very practical tool that can help us split strings into arrays according to the specified delimiter, which is very convenient when dealing with list data, tag content, or any structured text.However, when the delimiter is an empty string or does not exist in the target string, the behavior of the `split` filter shows some clever characteristics, understanding these characteristics is crucial for precise template control and avoiding potential errors.

2025-11-07

What are the main differences and application scenarios between the `make_list` filter and the `split` filter when splitting strings into arrays?

In AnQi CMS template development, it is often encountered that a string needs to be split into multiple parts for further processing or dynamic display.To meet this requirement, AnQiCMS template engine provides two very useful filters, `make_list` and `split`.Although they can both convert strings to arrays, there are obvious differences in their core functions, splitting logic, and applicable scenarios in actual use.Understanding these differences can help us handle content more efficiently and accurately.

2025-11-07

How to combine a dynamically generated array (such as a tag list) into a string with a specified delimiter for display in a template?

In website content operation, we often need to display a series of related information in the form of a list to users, such as all tags of an article, multiple characteristics of a product, or a set of image URLs.AnQiCMS's template system usually provides these data in the form of a dynamic array (or sometimes called slices, lists).

2025-11-07