In AnQiCMS template, how to elegantly truncate article content and display “…”?
AnQiCMS Based on its high-performance architecture based on the Go language and flexible template engine, it provides rich possibilities for content display.Our template system supports tags and filters similar to Django syntax, making content processing intuitive and efficient.To implement the truncation of the word count of the article content and display “…”, we mainly use the “filter” feature in the template.
Core Tool: Content Truncation Filter
AnQiCMS template includes a variety of powerful filters, of which the main ones used for content truncation are as follows:
truncatechars(Character slicing): 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 is necessary to note that,truncatecharsIt is 'inconsiderate', it may truncate in the middle of a word, even possibly damaging HTML tag structures, resulting in abnormal display.truncatewords(Sliced by words)If you are more concerned about the completeness of the content and do not want to truncate words in the middle, thentruncatewordsIt is a better choice. It will truncate by word, ensuring that each word is complete, but the final character length may vary slightly.
When the content you are dealing with is plain text (such as article titles, summaries, etc.), use it directlytruncatecharsortruncatewordsJust as it is. These filters will automatically add “…” to the end of the extracted text to indicate abbreviation.
Extract pure text content example:
Assuming you want to display the title and summary of articles on the list page, and you want the title to be up to 30 characters and the summary to be up to 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 }}The article title will be truncated to a maximum of 30 characters and will be followed by “…”.{{ article.Description|truncatewords:50 }}The article summary will be truncated to a maximum of 50 words and will be followed by “…”.
Process rich text (HTML) content truncation
In practical operations, the content of the article is often in rich text format, including images, links, bold text, and other HTML tags. If it is handled directlyarchive.Contentsuch fields are usedtruncatecharsortruncatewords, it may lead to incomplete truncation of HTML tags, thereby destroying the layout and style of the page, and even triggering parsing errors in the browser.
To solve this problem, AnQiCMS provides a special HTML security intercept filter:
truncatechars_html(securely intercept HTML by character):“ It is withtruncatecharssimilar, but with HTML smart recognition capability, ensuring that HTML tags remain complete and closed after extraction. This means it will correctly handle open tags and avoid the appearance of<div><b>文章内...such a situation.truncatewords_html(safely cut HTML by word): Similarly, it is withtruncatewordsSimilar, but also has HTML security processing capabilities to ensure that the HTML structure is not destroyed when cutting by words.
Special reminder:When usingtruncatechars_htmlortruncatewords_htmlWhen processing HTML content,Make sure to add after the clipping filter|safeFilter.|safeThe purpose of [auto] is to inform the template engine that this piece of content is safe HTML and does not require further escaping, so the browser can correctly parse and render it.
Extract HTML content example:
Suppose you want to display a brief preview of the article content in the article list and wish to retain 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 }}It willarchive.Content(Assumed to be rich text content of the article details) Truncated to a maximum of 150 characters.truncatechars_htmlWill intelligently handle the HTML tags within, for example, if it cuts halfway, it will automatically close all unclosed tags to avoid page chaos.- The last
|safeEnsure that the browser can render the extracted 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
- Choose the appropriate cutting method:For titles, short descriptions, and plain text,
truncatecharsortruncatewordssufficient. Forarchive.Contentorpage.Contentsuch rich text fields, make sure to use_htmlfilters ending with|safe. - and set a reasonable lengthThe length of the excerpt should be determined according to the layout and design style of your website.In responsive design, a long summary may appear redundant on small screens, while a short one may not provide enough information.Suggest previewing the effect on different devices.
- Combine condition judgment::Sometimes an article may not have an introduction, or the content may be too short, and it may seem redundant to excerpt. You can optimize the display by combining
{% if ... %}judgment:
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 thattruncatewordspure text extraction can be performed.
By flexibly using these content excerpt filters provided by AnQiCMS, you can easily create a content display effect that is both beautiful and practical, greatly enhancing the website's user experience and readability of the content.
Common Questions (FAQ)
1. Can the ellipsis be customized to other text? For example, “”?
AnQiCMS built-intruncatechars/truncatewordsThe HTML safe version filter, by default, will add “…” after extracting the content.Currently, these filters do not provide a direct parameter to customize this ellipsis.If you have special requirements, such as displaying "View More", you may need to implement more complex template logic (such as first judging whether the content exceeds the length and then manually concatenating strings) to achieve this, which 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乱码 or layout errors?
This is very likely because you forgot totruncatechars_htmlImmediately after the filter, use|safeFilter.truncatechars_htmlAlthough it can automatically 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, resulting in all HTML tags being displayed as<p>/<img>Entities such as these may cause garbled text or layout issues. Make sure your code is similar to