In website content management, we often need to present a long text (such as article abstracts, product descriptions) in a concise manner on the page, which not only saves space but also improves the user's browsing efficiency.If the long text is not processed and displayed directly in the list, it may cause the page to be disorganized and affect the user experience.The template engine of AnQiCMS provides flexible and powerful filter (Filters) functions, which can help us easily achieve string truncation and automatically add ellipses.
AnQiCMS Template String Truncation: Principle and Method
The template engine of Anqi CMS is similar to Django syntax, it processes and formats template variables through "filters". Filters use the pipe symbol|Connected at the end of a variable, it can facilitate operations on string, number, and other data types.For string truncation, AnQiCMS has built-in multiple practical filters that can meet the needs of different scenarios.
Basic Concepts: Filters and Template Variables
In the AnQiCMS templates, you will see something like{{ 变量 }}This syntax is used to output content. When we need to manipulate变量The content to be translated can be processed by introducing a filter, for example{{ 变量|过滤器名称:参数 }}.
Next, we will introduce several commonly used string truncation filters in detail.
Precisely control the number of characters:truncatechars
When you need to limit a long text precisely to a certain number of characters and want the ellipsis to be added automatically to the part that exceeds, truncatecharsThe filter is an ideal choice. It will truncate according to the number of characters you specify and add “…” at the truncation point. It is worth noting that these three ellipses will also be counted in the total character count.
- Usage:
{{ obj|truncatechars:数字 }} - Example:Assume
descriptionvariable's value is"AnQiCMS 是一个基于 Go 语言开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。"If you need to truncate the first 15 characters:{{ description|truncatechars:15 }}Output result:AnQiCMS 是一个基于 Go...(Please note that both Chinese characters and English characters are counted as single characters.)
Truncate by word:truncatewords
If you prefer to maintain the integrity of the text and avoid cutting off words in the middle, thentruncatewordsThe filter would be more appropriate. It will truncate according to the number of words you specify and add an ellipsis after the last complete word, and similarly, the ellipsis will not be counted in the word count.
- Usage:
{{ obj|truncatewords:数字 }} - Example:Continue using the above
descriptionVariable:{{ description|truncatewords:5 }}Output result:AnQiCMS 是一个基于 Go 语言开发...(It will try to retain the first 5 words and add an ellipsis at the end.)
Processing HTML content:truncatechars_htmlWithtruncatewords_html
In website content operation, we often encounter content generated by rich text editors with HTML tags. If used directly,truncatecharsortruncatewordsExtracting content of this type may result in the destruction of the HTML structure, chaotic page layout, and even abnormal display.
To solve this problem, AnQiCMS providestruncatechars_htmlandtruncatewords_htmlThese are two filters specifically designed to handle HTML content.They will intelligently retain the complete HTML tags while extracting text, ensuring the correctness of the page structure.
truncatechars_html:According to the number of characters, extract text containing HTML and retain the HTML structure.- Usage:
{{ obj|truncatechars_html:数字 }} - Example:Assume
contentvariable's value is"<p>这是一段<b>重要的</b>内容。</p><span>请注意查收。</span>"{{ content|truncatechars_html:10|safe }}(Note: When outputting HTML content, it is usually necessary to add)|safeFilter to prevent HTML tags from being escaped)Output result:<p>这是一段<b>重要的</b>内容...</p>(The filter will close any open tags, ensuring HTML validity.)
- Usage:
truncatewords_html:According to the number of words, extract text containing HTML and retain the HTML structure.- Usage:
{{ obj|truncatewords_html:数字 }} - Example:Continue using the above
contentVariable:{{ content|truncatewords_html:3|safe }}Output result:<p>这是一段<b>重要的</b>...</p>(It will identify word boundaries while maintaining the tag closure.)
- Usage:
Practice Case: Optimize Page Content Display
Suppose you are building an article list page, each article needs to display a brief description or summary.DescriptionThe field may come from the text input on the backend,Contentand the field is the complete content generated by the rich text editor with HTML.
{# 在文章列表循环中 #}
{% archiveList archives with type="page" limit="10" %}
{% for item in archives %}
<article class="article-item">
<h2 class="article-title"><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
{# 展示简洁描述,使用 truncatechars 避免过长 #}
<div class="article-description">
{{ item.Description|truncatechars:120 }}
</div>
{# 如果没有 Description,但有 Content,可以尝试截取 Content 的部分内容作为摘要 #}
{% if not item.Description and item.Content %}
<div class="article-teaser">
{# 对 HTML 内容进行截取,确保标签不被破坏,并加上 |safe 防止转义 #}
{{ item.Content|truncatewords_html:60|safe }}
</div>
{% endif %}
<div class="article-meta">
<span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
<span>浏览量:{{ item.Views }}</span>
</div>
</article>
{% empty %}
<p>暂时没有文章。</p>
{% endfor %}
{% endarchiveList %}
By flexibly using these slicing filters, you can ensure that the website presents content elegantly on different devices and layouts, enhancing the user experience.
Summary
AnQiCMS's template filters provide us with very convenient string processing capabilities.Whether it is precise to the number of characters or intelligent segmentation based on words, or even friendly handling of rich text HTML content, all can be easily achieved through simple filter syntax.Effectively utilizing these features will make your website content more professional and organized, and also more in line with users' reading habits.
Common Questions (FAQ)
1. Can the ellipsis style or content after truncation be customized (for example, changing “…” to “Read more”)?
AnQiCMS built-in truncation filter (such astruncatechars)提供的省略号样式是固定的,目前无法直接通过过滤器参数进行自定义。如果需要“阅读更多”这类文字,您可能需要手动实现:先通过sliceFilter a string of fixed length (without ellipsis), and then useifCheck if the original string exceeds the length, if it does, then append a custom text or link to the string after truncation.But this method requires you to manually handle character length calculation, which is relatively complex.
2. Why does the page layout become messy after I extract content with HTML tags?
This is usually because you have usedtruncatecharsortruncatewordsThis filter does not recognize HTML structure to process rich text content.They will truncate HTML tags indiscriminately, causing the tags on the page to close incorrectly, thereby causing layout chaos.truncatechars_htmlortruncatewords_htmlfilters, which intelligently retain the integrity of HTML tags to ensure that the page structure is not affected.
3. Can I apply multiple slicing filters to a variable?
AnQiCMS template filters support chaining (such as{{ item.Title|lower|truncatechars:10 }}),but it is usually different types of filters (such as first convert to lowercase and then cut). For the cutting function itself, you should choose the filter that best meets your needs (such astruncatecharsortruncatewords_html),而不是尝试同时应用多个截取过滤器。Because different truncation logic (by character, by word, whether to handle HTML) can produce different results, and the application may cause unexpected behavior or errors.