How to get only the first N characters of a string using the `slice` filter?

Calendar 👁️ 58

In website content display, we often need to cut a part of the long text as a preview, abstract, or to ensure the neat layout of the page. For example, displaying the article introduction on the article list page, or setting up for search engine optimization (SEO)meta descriptionWhen content is concerned, it is crucial to control the text length precisely. AnQiCMS (AnQiCMS) provides a powerful template engine with various flexible filters to help us easily meet these needs.

Today, let's delve deeply into one of the very practical and flexible filters -sliceIt can help us accurately obtain the first N characters of a string.

UnderstandingsliceFilter: The Tool for Text Trimming

sliceThe filter is a powerful tool in the AnQiCMS template used to slice a specified part of a string or array. Its basic syntax structure is{{ obj|slice:"from:to" }}.

  • obj: Represents the string or array variable you want to operate on.
  • from: Specifies the starting position of the substring (inclusive). If omitted, it starts from the beginning of the string or array.
  • to: Specify the end position to be cut (not included). If omitted, it cuts to the end of the string or array.

How can you accurately get the first N characters of a string? This isslicethe place where the filter shines. You just need tofromleave a part blank, andtoPosition specifies the number of characters you want to extract.

Example: Get the first 5 characters of a string.

Suppose we have a string."欢迎使用安企CMS模板"To get the first 5 characters, you can use it like thissliceFilter:

{% set myString = "欢迎使用安企CMS模板" %}
{{ myString|slice:":5" }}
{# 输出结果: 欢迎使用安企 #}

As you can see,slice:":5"Successfully extracted the part of the string from the first character to the fifth character (excluding the sixth one).

sliceThe actual application of the filter

In the content operation of AnQiCMS,slicethe filter has many practical scenarios.

1. Display of article list abstracts

On the homepage or category list page, we usually display a brief summary of each article. UsingsliceThe filter can conveniently control the length of the summary, maintaining a unified and beautiful page layout.

{# 假设您在循环文章列表,article.Description 包含文章简介 #}
{% archiveList archives with type="list" limit="10" %}
    {% for article in archives %}
        <div class="article-item">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            {# 截取简介的前 100 个字符,并手动添加省略号,以防截断后内容不完整 #}
            <p>{{ article.Description|slice:":100" }}...</p>
            <a href="{{ article.Link }}">阅读更多</a>
        </div>
    {% endfor %}
{% endarchiveList %}

2. Dynamically Generate Page Meta Description

Although the AnQiCMS backend can usually be set directly to set meta descriptions, but in some pages with dynamically generated content, or when you want the meta description to be automatically generated and controlled according to the article content, sliceThe filter can be used.

{# 假设 page.Content 是一个页面的完整内容 #}
<meta name="description" content="{{ page.Content|slice:":150" }}">

This way, even if the page content is long, the meta description can be kept within the reasonable length suggested by search engines, which helps to improve SEO performance.

3. Preview of long text in the user interface

When some user interface elements, such as sidebar recommended article titles are too long, or when the comments submitted by users need a brief preview,sliceThe filter can help you display key information within limited space.

{# 假设 item.LongTitle 是一个可能很长的标题 #}
<div class="sidebar-item">
    <a href="{{ item.Link }}" title="{{ item.LongTitle }}">
        {{ item.LongTitle|slice:":20" }} {# 截取前20个字符作为预览标题 #}
    </a>
</div>

slicewithtruncatecharsDifference

AnQiCMS also providestruncatecharsa filter, which can also be used to truncate strings, but it is different fromsliceThe filter has a key difference:

  • sliceFilter: It will truncate to the specified length and will not automatically add an ellipsis (…) at the end.This provides a purer text truncation control, suitable for scenarios that require precise control of text length and self-processing of ellipsis or no ellipsis.
  • truncatecharsFilter: After truncating to the specified length, if the original string exceeds this limit, an ellipsis (...) will be automatically added at the end. If you want the system to automatically handle the ellipsis after truncation,truncatecharsIt will be a more convenient choice.

Example comparison:

{% set text = "安企CMS是一个功能强大的内容管理系统" %}
{{ text|slice:":10" }}        {# 输出: 安企CMS是一个功 #}
{{ text|truncatechars:10 }}   {# 输出: 安企CMS是一... #}

Choose which filter to use depends on your specific needs. If you need complete control, including whether to display ellipses and the style of the ellipses, thenslicecombined with manual addition...Would be a better choice.

Summary

sliceThe filter is a seemingly simple but powerful tool in the AnQiCMS template language.By using it flexibly, we can easily achieve the truncation of the first N characters of a string, thus optimizing the content display of the website, improving user experience, and better supporting SEO strategies.Master this skill, and it will make you more proficient in website content operation and template design for AnQiCMS.


Frequently Asked Questions (FAQ)

1.sliceCan the filter be used to cut Chinese characters? Will there be any garbled characters?

Completely. The template engine of AnQiCMS supports UTF-8 encoded characters well,sliceThe filter handles the extraction of Chinese characters correctly, a Chinese character is usually calculated as a length unit, and there will not be a half character or garbled code issue.

2. UsesliceHow to automatically add an ellipsis (…) at the end of a string after it is truncated by the filter?

sliceThe filter does not automatically add an ellipsis. If you need this feature, you can use it whensliceAfter truncation, the ellipsis is manually concatenated, for example{{ article.Description|slice:":100" }}...Or, it is recommended to use directlytruncatecharsA filter that automatically adds an ellipsis at the end after truncating and checking the length.

3.sliceCan the filter be used to extract data of other types besides strings?

Yes,sliceThe filter can also be used to extract part of the elements in an array (slice). For example, if you have an array containing multiple itemsmyArrayYou can use{{ myArray|slice:"1:5" }}Get the elements from index 1 to 4 of the array (i.e., the 2nd to the 5th elements).

Related articles

How to extract elements from a specified range in AnQi CMS template?

In the powerful template system of Anqi CMS, we often need to precisely control the display of content.Whether it is an article list, product album, or custom data model, data is often presented in the form of an array.Sometimes, we may only need to display a part of the array, such as only showing the latest three records, or picking out a few images from a picture list.At this point, the `slice` filter provided by AnQi CMS comes in handy, as it helps us elegantly extract elements within a specified range from the array

2025-11-08

How to accurately extract the specified position element of a string in Anqi CMS template?

In AnQiCMS template development, we often need to flexibly handle text content, such as extracting the first few words of a long description as a summary, or extracting a specific part of the filename.AnQiCMS's powerful template engine provides a variety of practical filters (filter) to meet these needs, among which the "slice" filter is a powerful tool for precise string truncation.It allows us to easily extract any segment of content we want from a string or array.

2025-11-08

Default display template file for article detail page

The Anqi CMS provides a flexible and powerful template mechanism for handling the display of website article detail pages, allowing content operators and developers to finely control the presentation of each article according to actual needs.Understanding the search logic of the default template file is the basis for efficient content management and personalized customization.Firstly, the template files of Anqi CMS are all stored in the `/template` directory and use `.html` as the file extension.

2025-11-08

Which is the default display template file for the home page?

The homepage, as the first impression for users visiting your site, is of great importance.It carries multiple functions such as brand image, core information display, and user guidance.For those who are using or planning to use AnQiCMS (AnQiCMS) to build websites, understanding which file is behind the scenes controlling the display of this key page is the first step in customization and content optimization. AnQi CMS is committed to providing an efficient, customizable content management solution, naturally also providing you with great freedom to control this core page. Then

2025-11-08

How to use `slice` to get the last N elements of an array in AnQiCMS template?

In AnQiCMS template development, we often need to handle list or array type data, such as article lists, product lists, and so on.Sometimes, we might only be concerned with a part of these data, such as the latest few articles, or a specific number of elements at the end of the list.At this time, the `slice` filter built into AnQiCMS is particularly powerful and convenient.It allows us to flexibly extract elements from an array or string within a specified range.This article will thoroughly introduce how to use the `slice` filter in AnQiCMS templates

2025-11-08

How does the `slice` filter handle string or array index out of bounds situations?

In Anqi CMS template development, the flexibility of data display is crucial for building dynamic and user-friendly websites.The `slice` filter is a powerful and practical tool that helps us accurately extract part of the string or array content.However, when performing such operations, we are bound to encounter index out of bounds situations, that is, attempting to access a position beyond the data range.Fortunately, the `slice` filter of Anqi CMS has considered these edge cases and provided a set of elegant solutions.

2025-11-08

In AnQiCMS template, how to implement `slice` to extract a segment of content from a string?

In AnQi CMS template development, we often need to flexibly handle the displayed content, such as extracting key parts from a paragraph of text or simply displaying several items from the list.At this point, the `slice` filter is very practical.It can help us accurately extract a segment of content from the middle of a string or array (a slice in Go language).

2025-11-08

Does Go template's `slice` filter support negative indices? How to use it to slice in reverse order?

In AnQiCMS, templates are the key to building dynamic content, allowing us to flexibly display data.In the process of template development, it is often encountered that string or list (usually slice in Go template, which can be understood as an array) truncation operations need to be performed.AnQiCMS provides a powerful `slice` filter to handle such needs.### Deeply understand the basic usage of `slice` filter The `slice` filter is mainly used to extract specified elements from strings or lists

2025-11-08