In website content management, we often encounter such situations: In order to maintain the neat and unified layout of the page, we need to截取 overlong text content while not destroying its semantics or layout.Whether it is an article abstract, product description, or user review, appropriately controlling the length of text and adding ellipses can greatly improve user experience.The template engine of AnQiCMS (AnQiCMS) provides us with two very practical filters:truncatecharsandtruncatewordsAnd they handle variants of HTML content, which help us easily achieve this goal.
Elegantly extract plain text content:truncatecharswithtruncatewords
When your content is plain text, you can truncate it based on the number of characters or words.
Character-based truncation:
truncatecharsAs the name implies,truncatecharsThe filter truncates text based on the number of characters you specify. It counts from the beginning of the text and automatically adds an ellipsis at the end once the specified length is reached....This ellipsis character (…), which is three characters long, should also be counted in the total length.Usage example:Suppose we have a text
{{ item.Description }}.{{ item.Description|truncatechars:30 }}If
item.DescriptionThe content is 'Anqi CMS is an enterprise-level content management system developed based on the Go language, with powerful functions and simple deployment.'The above code may output: "AnQi CMS is an enterprise-level content management system based on Go language..." (The actual character count may vary due to encoding, but the logic is to count by characters).Extract by word:
truncatewordsAndtruncatewordsThe filter pays more attention to the integrity of words. It extracts words (separated by spaces) and when you specify how many words to truncate, it retains the first few complete words and then adds an ellipsis.This is especially useful for English content, as it can prevent words from being cut off halfway and becoming difficult to read.Usage example:
{{ item.Title|truncatewords:10 }}If
item.TitleThe content is 'AnQiCMS is a Go-based enterprise content management system with powerful features and easy deployment.' Then the above code may output: 'AnQiCMS is a Go-based enterprise content management system...'
Process content containing HTML: truncatechars_htmlwithtruncatewords_html
If your content contains HTML tags (such as rich text content in article details), use it directlytruncatecharsortruncatewordsIt may cause page layout confusion because they will indiscriminately truncate characters, possibly cutting off HTML tags in half. To solve this problem, Anqi CMS thoughtfully providestruncatechars_htmlandtruncatewords_htmlfilter.
These filters will intelligently close HTML tags while extracting text, ensuring that the page structure is not damaged.Similarly, they are also divided into character-based and word-based extraction.
Important reminder:When using these filters to process HTML content, be sure to add to the output|safeFilter. This is because the template engine, for security reasons, defaults to escaping all output to HTML (converting<to<etc.), if not added|safeYour HTML tags will be outputted as is, without being parsed by the browser.
Character-wise extraction of HTML:
truncatechars_htmlUsage example:{{ item.Content|truncatechars_html:100|safe }}If
item.ContentThe content is<strong>这是一段加粗的文字,后面还有很多内容,可能会被截断。</strong><p>这是一个段落。</p>Then the above code might output something like:“This is bold text, followed by a lot of content, which may be truncated.The result is... and HTML tags will close and render correctly.Extract HTML by word:
truncatewords_htmlUsage example:{{ item.SummaryHtml|truncatewords_html:20|safe }}This filter is compatible with
truncatechars_htmlSimilar, but the unit of extraction becomes words while maintaining the integrity of the HTML structure.
Application scenarios in practice
Mastered these filters, you can flexibly use them in the AnQiCMS template to optimize the display of your website content:
- Summary display on the article list page:Display the article title and a brief description on the homepage, category page, or search results page using
truncatecharsortruncatechars_htmlKeep the layout neat. - A brief introduction to the product details page:For long product features or descriptions, use the truncation filter to provide a quick preview.
- Control of SEO Meta Description:Even if the content editor has written a long description, you can ensure that the Meta Description length complies with the search engine's **practice** at the template level.
- User comments or messages are displayed uniformly:Long comments submitted by users are truncated and displayed in full after clicking, improving page loading speed and aesthetics.
Use tips
- Make good use of
|safeFilter:When you are sure that the output content has been processed by AnQiCMS and does not contain malicious code, for text containing HTML, be sure to use|safeto render correctly. - The difference in cutting effect between Chinese and English:For Chinese content,
truncatewordsIt considers the entire sentence as a 'word' (unless there is a space), therefore usuallytruncatecharsIt would be more suitable for truncating Chinese content by word count. English content can be chosen according to the actual situation. - Adjust the truncation length flexibly:By repeatedly testing the effect of different lengths, find the most suitable truncation length for your website design and user reading habits.
- Combine
ifSentence usage:You can use these filters more intelligently, for example, only truncate and display an ellipsis when the content actually exceeds the preset length, otherwise display it as it is, so as to avoid unnecessary ellipses.{% set max_length = 100 %} {% if item.Content|length > max_length %} {{ item.Content|truncatechars_html:max_length|safe }} {% else %} {{ item.Content|safe }} {% endif %}
Masteredtruncatechars/truncatewordsAnd its HTML variant, you can make your AnQiCMS website content more professional and friendly, whether it is plain text or rich media content, it can be presented to the user in a** posture.
Frequently Asked Questions (FAQ)
Q1: Why do I have to add|safeFilter?A1: This is because the AnQiCMS template engine, to prevent cross-site scripting (XSS) and other security issues, defaults to escaping all output variable content. This means it will convert<Convert to<,>Convert to>Wait. If you do not add|safe, the HTML tags themselves will be escaped, causing them to be recognized and rendered by the browser, but they will be displayed as plain text on the page. Add them.|safeThe filter tells the template engine that this part of the content is safe, does not need to be escaped, and can be output directly in HTML format.
Q2:truncatecharsandtruncatewordsWhen calculating the truncation length, will it include the automatically added ellipsis (...)?A2: Yes, they will include the automatically added ellipsis (...Three characters or a "word" unit are counted in the total truncation length. For example, if you usetruncatechars:10The total length of the output text (including the ellipsis) will be 10 characters.
Q3: What will the filter do if the set truncation length is longer than the actual text content?A3: If the truncation length you set is greater than or equal to the actual length of the text content, the filter will output the complete text content directly without adding an ellipsis.Only when the text content actually exceeds the length you set, will the filter truncate and add an ellipsis.