How to extract a specified part of a string or list in the AnQiCMS template?

Calendar 👁️ 70

In the daily operation of AnQi CMS, we often encounter scenarios where we need to display content in a refined manner.How to flexibly extract the part we want from a string or list, whether it is an article abstract, product parameter list, or a snippet of user comments, is the key to improving user experience and page cleanliness.As an experienced website operations expert, I deeply understand the power and flexibility of AnQiCMS based on the Go language and Django template engine. Today, let's delve into how to accurately extract the specified part of a string or list in AnQiCMS templates.

The core tool for accurate extraction:sliceFilter

AnQiCMS's template engine provides us with a variety of powerful filters, among which,sliceThe filter is undoubtedly the core tool for achieving precise extraction of specific parts of strings or lists. Its design is simple and efficient, and it can help us easily meet various data extraction needs.

Imagine you have a long article content, but you only want to display the first few dozen characters as a summary on the list page; or you have a list of product image URLs and you only want to display specific ones. At this time,slicea filter can come into play.

sliceThe filter is very intuitive to use, its basic syntax is{{ obj|slice:"from:to" }}. Here,objIt can be any string, array (slice) or list."from:to"It defines the part we want to extract:fromSpecify the starting index (including the element at this position),toSpecify the ending index (excluding the element at this position). It should be noted that the index starts from 0.

For example, if we have a string “Welcome to AnQi CMS, an efficient content management tool!” and we want to extract the part “AnQi CMS”, we can do it like this:

{# 假设我们有一个变量 articleTitle = "欢迎使用安企CMS,高效内容管理利器!" #}
{% set articleTitle = "欢迎使用安企CMS,高效内容管理利器!" %}
<p>完整标题:{{ articleTitle }}</p>
<p>截取后:{{ articleTitle|slice:"6:11" }}</p>

After running, the page will display:

完整标题:欢迎使用安企CMS,高效内容管理利器!
截取后:安企CMS

Here6:11Indicates starting from index 6 (i.e., the character “安”), to the position before index 11 (i.e., before the character “高”), thus extracting “安企CMS”.

sliceThe filter is also very flexible. If you want to truncate from the beginning to a certain position, you can omit it.fromFor exampleslice:":11"It will start from the beginning and go up to index 11. If you want to start from a position to the end, you can omit it.toFor exampleslice:"6:"It will start from index 6 and go up to the end of the string.

Moreover, it also supports negative indices, which is very useful in certain scenarios. For example,slice:"-3:"It indicates from the third character from the end to the end,slice:":-3"It means to cut from the beginning to the third character from the end.

For the slicing of a list or array,sliceThe usage of the filter is also the same. Suppose we usearchiveListThe tag got a list of documents and wants to only display the first three documents:

{% archiveList recentArchives with type="list" limit="10" %}
    {# 假设这里获取了10篇文档,我们想展示前3篇 #}
    {% for doc in recentArchives|slice:":3" %}
        <h3>{{ doc.Title }}</h3>
        <p>{{ doc.Description }}</p>
    {% endfor %}
{% endarchiveList %}

By|slice:":3"We cleverly truncated the original list, retaining only the first three documents to make the page display more focused.

辅助截取:firstandlastFilter

exceptsliceThis is a general way of truncation, AnQiCMS also provides a more concise way for usfirstandlastA filter used to quickly obtain the first character of a string or the first element of a list, as well as the last character of a string or the last element of a list.

it is more convenient to use them when you only need the first item in the list or the first character of a stringslicemore convenient.

{% set someString = "Hello AnQiCMS" %}
<p>字符串第一个字符:{{ someString|first }}</p>
<p>字符串最后一个字符:{{ someString|last }}</p>

{% archiveList docs with type="list" limit="5" %}
    {# 假设 docs 是一个文档列表 #}
    {% set firstDoc = docs|first %}
    <p>第一篇文档标题:{{ firstDoc.Title }}</p>
{% endarchiveList %}

The result will clearly display the "H" and "S" of the string, as well as the title of the first document.

Elegantly handle content overflow:truncatecharsandtruncatewordsFilter

In many cases, we truncate strings to generate content summaries and to automatically add ellipses when the content is too long. AnQiCMS provides this feature.truncatecharsandtruncatewordsA series of truncation filters.

truncatecharsThe filter will truncate by character count, and if the content exceeds the specified character count, it will add “…” at the end.It should be noted that the specified length includes the ellipsis. For example,|truncatechars:20It ensures that the output string (including ellipsis) is no more than 20 characters.

truncatewordsThe filter truncates based on the number of words, and an ellipsis is added when the content overflows.

These filters are particularly suitable for displaying summaries on article list pages, ensuring the layout is neat and suggesting the completeness of the content.

{% set longDescription = "AnQiCMS 是一个基于 Go 语言开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。" %}
<p>字符截断摘要:{{ longDescription|truncatechars:30 }}</p>
<p>单词截断摘要:{{ longDescription|truncatewords:10 }}</p>

The output may look like:

字符截断摘要:AnQiCMS 是一个基于 Go 语言开发的企业级内容...
单词截断摘要:AnQiCMS 是一个基于 Go 语言开发的企业级内容管理系统...

For content containing HTML tags, AnQiCMS also takes this into account and providestruncatechars_htmlandtruncatewords_htmlFilters that can intelligently maintain the integrity of HTML tags while truncating, avoiding page structure chaos due to truncation.

Flexible combination:splitwithjoinFilter

Sometimes, we need to perform more complex operations on a string, such as when it is itself a comma-separated string, and we want to treat it as a list to slice and then reassemble. At this time,splitandjoinThe filter can be used withsliceto perfectly match.

splitThe filter can split a string into an array using a specified delimiter. For example,"apple,banana,orange"|split:","it will get an array containing three elements.

joinThe filter is exactly the opposite, it can concatenate an array into a string using a specified separator.

{% set tagsString = "SEO,网站优化,内容营销,Go语言" %}
{# 先将字符串拆分成数组,然后截取前两个,再重新拼接 #}
{% set firstTwoTags = tagsString|split:","|slice:":2"|join:" / " %}
<p>精选标签:{{ firstTwoTags }}</p>

The output will be:

精选标签:SEO / 网站优化

This combination operation greatly expands our ability to handle data in templates, making complex string and list operations simple and intuitive.

In summary, the template engine of AnQiCMS provides website operators with extremely flexible and powerful content control capabilities. Whether it is precise to the character level,sliceTo truncate or to generate an abstract?truncatecharsOr withsplit/joinCooperating to implement complex data conversion, these filters are indispensable tools in our hands.By proficiently using these features, we can ensure that the display of website content always meets the design expectations and enhances the user browsing experience.

Frequently Asked Questions (FAQ)

1. Why should I usesliceinstead oftruncatecharsto truncate a string?SelectsliceOrtruncatecharsIt depends on your specific needs. If you need to extract a specific range of content from a string and do not want to automatically add an ellipsis (...) after the cut, thensliceIs the more suitable choice. It provides pure range extraction.truncatechars(ortruncatewordsIt is used specifically for generating summaries. When the content is too long, it will automatically add an ellipsis at the end and has_htmlVariants can intelligently handle HTML tags without destroying the structure. In short,sliceFocus on “which part to take”,truncatecharsFocus on “how long and with hints”.

2.sliceCan the filter correctly handle strings containing Chinese characters?Yes, the template engine of AnQiCMS takes into account the characteristics of UTF-8 encoding when processing strings, thereforesliceThe filter can correctly cut Chinese characters by character. A Chinese character is considered as one character, regardless of how many bytes it occupies internally, and you can cut Chinese strings accurately by index just like cutting English characters.

3. If I givesliceThe filter passes infromortoWhat happens if the index is out of the actual length of the string or list?AnQiCMS'sliceThe filter will handle safe boundary processing. IffromThe index is greater than the actual length, ortoThe index is less thanfromAn index usually returns an empty string or an empty list. IftoThe index is out of range, it will automatically truncate to the end of the string or list.This design avoids template rendering errors caused by index out of bounds, making our development more robust.

Related articles

How does the AnQiCMS template handle the escaping and unescaping of HTML content?

As an experienced website operations expert, I am well aware of the subtle balance between content safety and flexible display.In AnQiCMS such an efficient and secure content management system, understanding how its templates handle the escaping and unescaping of HTML content is crucial for building both aesthetically pleasing and secure user experiences.AnQiCMS is developed based on Go language, its template engine inherits many safety design concepts of modern web frameworks when processing HTML, including automatic escaping of HTML content.

2025-11-07

How to set a custom template for the document detail page or category list page of AnQiCMS?

As an experienced website operations expert, I am well aware that the flexibility and customizability of a content management system (CMS) are crucial for the long-term development of the website and the user experience.AnQiCMS (AnQiCMS) provides an excellent solution in this aspect with its powerful functions and ease of use.Today, let's delve into how to set up custom templates for your document detail page or category list page in AnQiCMS, making your website content display more personalized and professional.

2025-11-07

How does the AnQiCMS template support adaptive, code adaptation, and PC+mobile mode?

## AnQiCMS template: How to ride the multi-end content display with wisdom and flexibility?In today's fast-paced digital world, it is common for users to access websites through various devices.As experienced website operators, we know that whether a website can provide a smooth and high-quality experience on PCs, tablets, mobile phones, and other terminals is directly related to user retention and business conversion.

2025-11-07

How to define an AnQiCMS template configuration file (config.)?

As an experienced website operations expert, I fully understand the importance of a flexible and powerful content management system for enterprises.AnQiCMS is an excellent platform committed to providing efficient and customizable solutions.In the template ecosystem of AnQiCMS, a seemingly insignificant but powerful file - `config.`, plays a crucial role.It not only defines the basic attributes of the template, but also profoundly affects the behavior and performance of the template in the system.

2025-11-07

How to implement string content replacement in AnQiCMS template?

As an experienced website operations expert, I know that flexibility and efficiency are the key to success in daily content management.How to quickly and accurately adjust the string content on the page in terms of content display, whether it is for SEO optimization, brand consistency, or to meet the ever-changing market needs, it is a core skill we must master.Today, let's delve deeply into how the AnQiCMS template cleverly implements the replacement function of string content, empowering your content operation.

2025-11-07

How to get the current website's system configuration information in AnQiCMS template (such as website name, Logo)?

As an experienced website operations expert, I am happy to discuss with you how to efficiently and flexibly obtain the current system configuration information of the website in AnQiCMS templates.This is not only the foundation of template development, but also the key to ensuring the consistency and maintainability of website information.AnQiCMS is an enterprise-level content management system developed based on the Go language, its concise and efficient design philosophy is also reflected in the use of template tags, making the call of technical information in the template layer extremely intuitive.### Cleverly utilize the `system` tag

2025-11-07

How to get the current page's TDK (Title, Description, Keywords) information in AnQiCMS template?

As an experienced website operation expert, I am well aware that TDK (Title, Description, Keywords) is crucial for the search engine optimization (SEO) of any website, as it is like the facade of the website and a guide for search engines.A meticulously optimized TDK that can make your website stand out in the vast sea of online information, attracting targeted users to click and bringing valuable traffic.

2025-11-07

How does the AnQiCMS template handle arithmetic operations on numbers?

Under the powerful system of AnQi CMS, content operation is far more than just piles of text and images.For modern websites, especially for e-commerce, data display, or scenarios requiring dynamic calculations, the ability to perform numerical operations directly in templates is particularly important.It makes our pages no longer static display boards, but intelligent interfaces that can respond in real-time to data.

2025-11-07