How to elegantly truncate article content and display “…” in the AnQiCMS template?
In website content operation, we often need to display the abstract of articles, products, or single-page content on list pages, aggregation pages, or search results.These summaries not only make the page look neater, but also help visitors quickly understand the content outline, thereby deciding whether to click to read the full text.However, it is obviously impractical to display the full content directly, which gives rise to a common requirement: how to truncate the text of an article and add “…” at the end to indicate that the reader's content has not yet ended?
AnQiCMS with its high-performance architecture based on the Go language and flexible template engine, provides rich possibilities for content display.Our template system supports syntax similar to Django's tags and filters, making content processing intuitive and efficient.To implement the truncation of the article content and display “…”, we mainly use the filter function in the template.
Core Tool: Content Truncation Filter
AnQiCMS has built-in a variety of powerful filters, among which the main ones used for content truncation are as follows:
truncatechars(By character cut)This filter will truncate the string according to the number of characters you specify. It is very suitable for scenarios that require precise control of length. But it should be noted that,truncatecharsIt is 'unfeeling', it may be cut off in the middle of a word, and even may destroy the HTML tag structure, causing display anomalies.truncatewords(Word-wise truncation)If you are more concerned with the integrity of the content and do not want to split words in the middle, thentruncatewordsIs a better choice. It will cut by word, ensuring each word is complete, but the final character length may be slightly floating.
When the content you are processing is plain text (such as article titles, summaries, etc.), use it directlytruncatecharsortruncatewordsThese filters will automatically add “...” at the end of the extracted text to indicate omission.
Extract pure text content example:
Suppose you want to display the title and summary of the article on the list page, and you want the title to be displayed with a maximum of 30 characters, and the summary to be displayed with a maximum of 50 words. You can write the template code like this:
<div class="article-item">
<h3><a href="{{ article.Link }}">{{ article.Title|truncatechars:30 }}</a></h3>
<p>{{ article.Description|truncatewords:50 }}</p>
<a href="{{ article.Link }}" class="read-more">阅读更多</a>
</div>
In this example:
{{ article.Title|truncatechars:30 }}Truncate the article title to a maximum of 30 characters and add “…” at the end.{{ article.Description|truncatewords:50 }}Truncate the article summary to a maximum of 50 words and add “…” at the end.
Translate rich text (HTML) content truncation
In practice, article content is often in rich text format, including images, links, bold and other HTML tags. If you directly usearchive.Contentsuch fieldstruncatecharsortruncatewordsThis could lead to incomplete truncation of HTML tags, thereby destroying the page layout and style, and even causing browser parsing errors.
To solve this problem, AnQiCMS provides a special HTML security interception filter:
truncatechars_html(Intercept HTML by character): It is related totruncatecharsSimilar, but with HTML smart recognition capabilities, it ensures that HTML tags remain complete and closed after extraction. This means it correctly handles open tags and avoids issues.<div><b>文章内...such a situation.truncatewords_html(Safely extract HTML by word): Similarly, it is withtruncatewordsSimilar, but also has HTML security processing capabilities, ensuring that the HTML structure is not destroyed when cutting words.
Special reminder:When usingtruncatechars_htmlortruncatewords_htmlWhen processing HTML content,Must add after the extraction filter|safeFilter.|safeThe purpose is to inform the template engine that this content is safe HTML, which does not require further escaping, so that the browser can correctly parse and render it.
An example of extracting HTML content:
Suppose you want to display a brief preview of the article content in the article list and want to keep the HTML format:
<div class="article-preview">
<h4><a href="{{ archive.Link }}">{{ archive.Title }}</a></h4>
<div class="content-summary">
{# 截取文章内容前150个字符,并确保HTML结构完整 #}
{{ archive.Content|truncatechars_html:150|safe }}
</div>
<a href="{{ archive.Link }}" class="view-detail">查看详情</a>
</div>
In this example:
{{ archive.Content|truncatechars_html:150|safe }}Willarchive.Content(Assuming it is the rich text content of the article detail) truncated to a maximum of 150 characters.truncatechars_htmlIt can intelligently handle the HTML tags within, for example, if it is cut in half, it will automatically close all unclosed tags to avoid page chaos.- The last
|safeMake sure the browser can render the captured HTML code correctly, rather than displaying it as plain text.
If you prefer to extract HTML content by word:
<div class="product-teaser">
<h5><a href="{{ product.Link }}">{{ product.Title }}</a></h5>
<div class="description-teaser">
{# 截取产品描述前30个单词,并确保HTML结构完整 #}
{{ product.Description|truncatewords_html:30|safe }}
</div>
<a href="{{ product.Link }}" class="learn-more">了解更多</a>
</div>
Some practical suggestions
- Select the appropriate truncation methodFor titles, brief descriptions, and other plain text,
truncatecharsortruncatewordsthey are sufficient. Forarchive.Contentorpage.Contentsuch rich text fields, it is imperative to use_htmlfilterers ending with, and combine with|safe. - reasonable lengths set: The length of the excerpt should be determined based on the layout and design style of your website.In responsive design, a long summary may appear redundant on small screens, and a short one may not provide enough information.Suggest previewing the effect on different devices.
- Combine conditional judgment: Sometimes, an article may not have an introduction or be very short, and cutting it may seem redundant. You can combine
{% if ... %}judgment to optimize the display:
Here{% if archive.Description|length > 0 %} <p>{{ archive.Description|truncatewords:50 }}</p> {% elif archive.Content|length > 0 %} <p>{{ archive.Content|striptags|truncatewords:50 }}</p> {# 先剥离HTML标签,再截取纯文本 #} {% else %} <p>暂无内容摘要。</p> {% endif %}|striptagsThe filter can first strip all tags from the HTML content, leaving only plain text, so it can betruncatewordsused for plain text extraction.
By flexibly using these content extraction filters provided by AnQiCMS, you can easily create a content display effect that is both beautiful and practical, greatly enhancing the user experience and readability of the website.
Frequently Asked Questions (FAQ)
1. Can the ellipsis symbol after the truncation be customized to other text? For example, "[View More]"?
Built-in to AnQiCMStruncatechars/truncatewordsand its HTML safe version filter, it will add “…” by default after extracting the content.Currently, these filters do not provide direct customization of the ellipsis parameter.If you have special requirements, such as displaying “[View More]”, it may be necessary to implement more complex template logic (such as first determining if the content exceeds the length, then manually concatenating strings) to achieve this, but this will increase the complexity of the template.In most cases, we recommend using the default “…” symbol to maintain conciseness and consistency.
2. Why did I use HTML content?truncatechars_htmlAfter truncation, why does the front-end page still display garbled text or layout errors?
This is likely because you forgot totruncatechars_htmlAfter using the filter, what should be used next?|safefilter.truncatechars_htmlAlthough it can intelligently close HTML tags, what it outputs is still a string. If there is no|safeThe filter tells AnQiCMS template engine that this is a safe HTML fragment, the engine will escape it as plain text, causing all HTML tags to be displayed as<p>/<img>Entity characters may cause garbled text or layout issues. Make sure your code is similar to