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.