In website content management, we often need to present a long text (such as an article abstract, product description) in a concise way on the page, which can not only save space but also improve the user's browsing efficiency.If long text is not processed and displayed directly in the list, it may lead to a chaotic page layout and affect the user experience.The template engine of AnQiCMS (AnQiCMS) provides flexible and powerful filter (Filters) functions that can help us easily implement string truncation and automatically add ellipses.
String slicing in AnQiCMS template: principle and method
The template engine of AnqiCMS is similar to Django syntax, it processes and formats template variables through 'filters'. Filters use the pipe character|Connected to the variable, it can conveniently operate on data types such as strings, numbers, etc.For string truncation, AnQiCMS has built-in a variety of practical filters that can meet the needs of different scenarios.
Basic Concept: Filters and Template Variables
In AnQiCMS templates, you will see something like{{ 变量 }}This syntax is used to output content. And when we need to handle this变量When content needs special processing, filters can be introduced, for example{{ 变量|过滤器名称:参数 }}.
Next, we will introduce several commonly used string truncation filters.
Exact control of character count:truncatechars
When you need to limit a long text precisely to a certain number of characters and want to automatically add an ellipsis to the part that exceeds,truncatecharsThe filter is a good 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 are also counted in the total character count.
- How to use:
{{ obj|truncatechars:数字 }} - Example:Assume
descriptionthe value of the variable is"AnQiCMS 是一个基于 Go 语言开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。"If you need to cut 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 here.
Cut by word:truncatewords
If you prefer to maintain the integrity of the text and avoid breaking 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 the ellipsis will not be counted in the word count.
- How to use:
{{ obj|truncatewords:数字 }} - Example:Continue using the above
descriptionVariable:{{ description|truncatewords:5 }}Output Result:AnQiCMS 是一个基于 Go 语言开发...(It will try to keep the first 5 words and add an ellipsis at the end.)
Process 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 lead to the destruction of the HTML structure, disordered page layout, and even abnormal display.
To solve this problem, AnQiCMS providedtruncatechars_htmlandtruncatewords_htmlThese filters are 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:Extract text containing HTML based on the number of characters while retaining the HTML structure.- How to use:
{{ obj|truncatechars_html:数字 }} - Example:Assume
contentthe value of the variable 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 to ensure HTML validity.)
- How to use:
truncatewords_html:Extract text containing HTML based on the number of words, while preserving the HTML structure.- How to use:
{{ obj|truncatewords_html:数字 }} - Example:Continue using the above
contentVariable:{{ content|truncatewords_html:3|safe }}Output Result:<p>这是一段<b>重要的</b>...</p>(It will recognize word boundaries while keeping the tags closed.)
- How to use:
Case Study: Optimize Page Content Display
Suppose you are building an article list page, each article needs to display a brief description or abstract. The article'sDescriptionThe field may come from the background text input, whereasContentThe field is the full content generated by the rich text editor, which includes 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 filtering tools, you can ensure that the website presents content elegantly across different devices and layouts, enhancing user experience.
Summary
AnQiCMS template filters provide us with very convenient string processing capabilities.Whether it is a precise cut to the number of characters or an intelligent cut based on words, or even a friendly handling of rich text HTML content, it can be easily realized through simple filter syntax.Reasonably utilizing these features will make your website content display more professional, neat, and more in line with user reading habits.
Frequently Asked Questions (FAQ)
1. Can you customize the ellipsis style or content after truncation (for example, changing “…” to “Read more”)?
AnQiCMS built-in truncation filter (such astruncatechars)The ellipsis style provided is fixed and cannot be customized directly through filter parameters. If you need text like sliceFilter to extract a fixed-length string (without an ellipsis) and then useifCheck if the original string length exceeds, if it does, then concatenate a custom text or link to the end of the truncated string.But this method requires you to handle character length calculation yourself, 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 indiscriminately truncate HTML tags, causing the labels on the page to close incorrectly, thereby causing layout chaos.Be sure to use for content containing HTMLtruncatechars_htmlortruncatewords_htmlfilters, which intelligently retain the integrity of HTML tags, ensuring that the page structure is not affected.
3. Can I apply multiple slicing filters to a variable?
AnQiCMS template filters support chained calls (for example{{ item.Title|lower|truncatechars:10 }}), but it is usually different types of filters (such as first convert to lowercase and then cut off). For the cutting function itself, you should choose the filter that best meets your needs (such astruncatecharsortruncatewords_html),Instead of trying to apply multiple extraction filters at the same time. Because different extraction logic (character-based, word-based, whether to handle HTML) can produce different results, and applying them simultaneously may lead to unexpected behavior or errors.