How to truncate article content in AnQiCMS template and display “...”?

Calendar 👁️ 82

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:

  1. 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.

  2. 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:

  1. 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.

  2. 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

  1. 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.
  2. 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.
  3. 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:
    
    {% 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 %}
    
    Here|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&lt;p&gt;/&lt;img&gt;Entity characters may cause garbled text or layout issues. Make sure your code is similar to

Related articles

How to implement dynamic display and link jump of the website homepage Banner carousel in AnQiCMS?

In website operation, an attractive homepage banner carousel is a key element to enhance user experience, highlight core content, and guide user behavior.AnQiCMS as an efficient and flexible content management system provides an intuitive way to manage and display these dynamic contents.Next, we will explore how to easily implement the dynamic display and link jump of the website homepage Banner slideshow using AnQiCMS.

2025-11-09

How to call and display the contact information set in the background of the AnQiCMS website at the bottom, such as phone number, email?

Clearly display contact information at the bottom of the website, which is crucial for improving user experience and building trust.AnQiCMS as an efficient content management system takes this into full consideration, providing an intuitive and flexible way to manage and display this key information, such as phone numbers and email addresses. ### One, AnQiCMS backend contact settings and management In the AnQiCMS backend management interface, you can easily find and configure the website's contact information.

2025-11-09

How to display the link to the previous and next article on the article detail page in AnQiCMS template?

In AnQiCMS, adding "Previous Article" and "Next Article" navigation links to the article detail page is a key factor in enhancing user experience and guiding users to delve deeper into the website content.The powerful template system of AnQiCMS makes this feature very intuitive and efficient, it uses syntax similar to Django template engine, making it easy for developers to master. AnQiCMS template files are usually suffixed with `.html` and stored in the `/template` directory.

2025-11-09

How to integrate MathJax or Mermaid.js in AnQiCMS page to display mathematical formulas and flowcharts?

Integrate MathJax and Mermaid.js on AnQiCMS page: Easily display mathematical formulas and flowcharts AnQiCMS is an efficient and flexible content management system that excels in meeting various content display requirements.With the increasing richness of technical content, many users may encounter the need to elegantly display mathematical formulas and flowcharts on websites.AnQiCMS integrates its built-in Markdown editor and flexible template support, allowing integration with MathJax and Mermaid.js

2025-11-09

How does AnQiCMS ensure that each site's page content is displayed independently under multi-site management?

AnQiCMS was designed from the beginning to fully consider the needs of enterprises and content operators for multi-site management and is committed to providing a highly efficient and independent solution.When you create multiple sites in AnQiCMS, the system ensures that the page content of each site can be displayed independently, without interference, and also allows for limited cross-site content interaction when needed.

2025-11-09

How to display the category name and link of the article belonging to the AnQiCMS document detail page?

In AnQiCMS, we often hope that visitors can clearly see the category name of this article when browsing the document details, and can conveniently click on the category link to further explore more content under the same category.This not only optimizes the user experience and makes the website structure more intuitive, but also helps search engines better understand the content hierarchy of the website, improving SEO effects. To implement this feature on the document detail page of AnQiCMS, we need to make some simple modifications to the template file.AnQiCMS uses something similar to Django

2025-11-09

How to process thumbnails and display images of different sizes in AnQiCMS templates?

Managing website content in AnQiCMS, image processing is undoubtedly a key factor in improving user experience and page loading speed.A website that can intelligently present thumbnails of images in appropriate sizes for different display scenarios can not only greatly improve the page response speed but also make the visual layout more coordinated and beautiful.The AnQi CMS provides a powerful and flexible image thumbnail processing mechanism, which can be easily implemented, whether through unified settings in the background or on-demand calls in the frontend template.### Back-end Content Settings

2025-11-09

How to use the `pagination` tag of AnQiCMS to implement pagination navigation on the article list page?

In website content operation, the pagination navigation of the article list page is a key link to improve user experience and optimize search engine crawling efficiency.AnQiCMS as a feature-rich enterprise-level content management system, provides us with a simple and efficient `pagination` tag, making it easy to implement this feature.Next, we will discuss in detail how to use the `pagination` tag to implement page navigation on the article list page of AnQiCMS.

2025-11-09