In AnQiCMS template development, we often need to control the length of article titles or descriptions to maintain a tidy and unified visual effect on list pages, card layouts, or other compact display areas.At the same time, when the content is truncated, it is customary to add an ellipsis to提示 readers that there is more content here.AnQiCMS's powerful template engine is built-in with rich filters (Filters), making this task extremely simple and efficient.
Understand the need for content extraction
Whether it is an article list, recommendation position, or SEO meta description, content length limits are a common challenge in front-end display.Long titles or descriptions can break the page layout and affect aesthetics;That a concise and unified display can enhance user experience and make the page look more professional.Therefore, flexibly extract the article title (Title) or description (DescriptionThe ellipsis is automatically added, which is an indispensable skill in template development.
Core Tool:truncatecharsFilter
The AnQiCMS template engine providestruncatecharsFilter, this is the most direct and commonly used method to implement title and description truncation with an ellipsis. Its function is to truncate the string based on the specified character length, and if the length of the original string exceeds this limit, it will automatically add an ellipsis at the end (...)
The method of use is very intuitive, you just need to add a pipe symbol after the variable you need to process|Invoketruncatecharsand pass the length of the characters you want to retain.
For example, if you want to truncate the article title to 25 characters:{{ item.Title | truncatechars:25 }}
Assumeitem.TitleThe original text is "AnQiCMS Template Content Extraction Guide: Say goodbye to verbosity, present article titles and descriptions accurately", then throughtruncatechars:25After processing, the output may be: “AnQiCMS template content extraction guide: Say goodbye to long, concise…”
It should be noted that,truncatecharsThe filter counts the length according to UTF-8 characters when calculating.This means that even Chinese characters are counted as one character for calculation, which is very friendly and accurate for the layout control of Chinese websites.
Process content containing HTML: truncatechars_html
In some cases, the article description (Description) may contain a small amount of HTML tags, such as bold, links, etc. If used directlytruncatecharsTruncation may cause HTML tags to be cut off, thereby destroying the page structure or style.
For this situation, AnQiCMS providestruncatechars_htmlFilter. It istruncatecharsThe function is similar, but it will intelligently identify and retain the integrity of HTML tags, avoiding HTML structure errors caused by truncation, and add ellipses at appropriate positions.
While usingtruncatechars_htmlWhen, it is usually recommended to match with|safeA filter to ensure that truncated and processed HTML content can be correctly parsed by the browser, rather than output as plain text.
For example, if you need to truncate the article description containing HTML to 80 characters and ensure that the HTML structure is not broken:{{ item.Description | truncatechars_html:80 | safe }}
Another option: truncate by wordtruncatewordswithtruncatewords_html
In addition to character truncation, AnQiCMS also provides a word truncation filter:truncatewordsandtruncatewords_htmlThese filters are particularly suitable for English content because they attempt to truncate at word boundaries to maintain the semantic integrity of the text and avoid cutting off the middle of a word.
The way to use withtruncatecharsSeries is similar, but the number of words you want to keep is passed in:
- Extract plain text by word:
{{ item.Title | truncatewords:10 }} - Extract HTML content by word:
{{ item.Description | truncatewords_html:20 | safe }}
Actual application scenarios and code examples
In the article list page, you will usually loop through multiple articles, and at this time, you can flexibly use these filters in the loop body:
{# 假设这是文章列表的循环体 #}
{% archiveList archives with type="page" limit="10" %}
{% for item in archives %}
<div class="article-card">
<a href="{{item.Link}}">
{# 截取标题到25个字符,并添加省略号 #}
<h3 class="article-title">{{ item.Title | truncatechars:25 }}</h3>
{# 截取描述到60个字符,如果包含HTML则智能处理,并添加省略号 #}
<p class="article-description">{{ item.Description | truncatechars_html:60 | safe }}</p>
<span class="read-more">阅读更多</span>
</a>
</div>
{% empty %}
<p>暂时没有文章内容。</p>
{% endfor %}
{% endarchiveList %}
In this code,h3The article title within the tag will be truncated to 25 characters, and an ellipsis will be displayed if it exceeds.pThe article description within the tags will be truncated to 60 characters, and even if the description contains HTML tags,truncatechars_htmlWe will also try to ensure the integrity of these tags, to avoid the page display errors. The last one,|safeThe filter is to ensure that the browser can correctly render these texts that may contain HTML.
Summary
AnQiCMS template filter provides great convenience for website content operators. By simply applyingtruncatecharsandtruncatechars_htmlWith the filter, you can easily control the length of article titles and descriptions, not only optimizing the visual display effect of the front end, but also improving the user reading experience.Flexible use of these tools will make your website content management more efficient and beautiful.
Frequently Asked Questions (FAQ)
1. Why is it usually necessary to use both when extracting content that includes HTML?truncatechars_htmland|safeFilter?
truncatechars_htmlThe filter can intelligently extract strings containing HTML tags, preventing the tags from being destroyed.However, AnQiCMS's template engine defaults to escaping all output content to prevent XSS attacks.If the content you extract already contains HTML tags (such as<p>/<strong>), and if you want these tags to be parsed by the browser instead of displayed as plain text, then intruncatechars_htmlAfter that, it still needs to be added|safeThe filter is used to explicitly tell the template engine that this content is safe and does not need to be escaped.
2. What will happen if the length I set for the cut is longer than the actual title or description?
If the set cut length (for example,truncatechars:50If the length is greater than or equal to the actual length of the original string, thentruncatechars(ortruncatechars_htmlThe filter will not truncate the content or add an ellipsis. It will directly output the original full content.
3.truncatecharsandtruncatewordsWhat are the differences between filters? When should they be used?
truncatecharsis sorted bycharacterTo truncate content, whether it is English letters, numbers, or Chinese characters, it is counted as one character. It is truncated directly when it reaches the specified length, which may cut off the middle of a word. AndtruncatewordsThen it is according towordsTo extract content, it will try to truncate at word boundaries to maintain the integrity of each word.
In most cases:
- If your content is inChineseEnglish, or have strict pixel-level layout requirements for character count,
truncatecharsIs a more precise choice. - If your content is inEnglishEnglish, and hope to keep the integrity of the words when truncating,
truncatewordsIt will provide a better reading experience. The corresponding HTML versiontruncatechars_htmlandtruncatewords_htmlIt is used to handle content with HTML tags.