How to truncate a long text content while displaying and automatically add an ellipsis?

Calendar 78

In website operation, we often need to display various text content on the page, such as the abstract of article lists, previews of product introductions, or brief descriptions of a detailed page.Faced with long-form content, how can one elegantly present its core information within a limited space and guide users to click for more details, which is a common requirement.It is particularly important to truncate long text content and automatically add an ellipsis.

AnQiCMS (AnQiCMS) is an efficient and flexible content management system that fully considers these user needs, providing a very convenient and powerful content filtering mechanism to help us easily achieve this goal.By using these built-in filters, we can not only optimize the page layout and enhance visual aesthetics, but also significantly improve user experience and make information transmission more efficient.

Why do you need to truncate long text content?

Content truncation and automatic addition of ellipses is a key factor in improving website user experience and page performance.

First, it can effectively optimize the page layout, avoiding information overload.Imagine a list of articles, where if the complete text of each article is displayed directly, the page would become too long and users would find it difficult to quickly browse and find content that interests them.By truncating, we can display more entries within limited screen space, enhancing the compactness and professionalism of the page.

Secondly, extracting content can improve readability and attractiveness. A concise summary is easier for users to quickly digest and stimulate their desire to click 'Read More'.This is like the cover blurb of a book, with just the right amount of white space and suspense, which is an important means of guiding users to delve deeper.

In addition, for search engine optimization (SEO), carefully extracted content snippets are often used as page meta descriptions (Meta Description) or search results summaries, which helps to attract users to click on the search results, thereby increasing the website's traffic.

The solution provided by AnQiCMS: Content Extraction Filter

The AnQi CMS is built-in with a variety of flexible filters, specifically designed for handling the truncation and formatting of long text content. These filters can intelligently judge the length of the text and automatically insert ellipses (...), and when using it, we also need to pay attention to distinguishing between plain text and rich text containing HTML tags to ensure the integrity of the extracted structure.

The AnQi CMS mainly provides the following core filtering extractors:

  1. truncatechars: Cut by character count.
  2. truncatewords: Cut by word count.
  3. truncatechars_html: Safely cut by character count in HTML.
  4. truncatewords_html: HTML safely truncates by word count.

Next, we will learn in detail about the usage of these filters.

1.truncatechars: Truncate by character count

truncatecharsThe filter will truncate the string based on the number of characters you specify. It is important to note that it will automatically add an ellipsis (...) is included in the total length. If the length of the original content is less than or equal to the specified length, no truncation will be performed.

Usage: {{ 变量名|truncatechars:字符数量 }}

Example:Assuming we have a long text: "Anqi CMS is an enterprise-level content management system developed based on the Go language, committed to providing an efficient, customizable, and scalable content management solution."

<p>
    {{ "安企CMS 是一个基于 Go 语言开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。"|truncatechars:20 }}
</p>

Display result:AnQi CMS is an enterprise-level application developed based on the Go language...

2.truncatewords: Truncate by word count

truncatewordsThe filter then truncates the string based on the number of words you specify.Its advantage lies in not truncating a word, but retaining the complete word and adding an ellipsis after the last complete word.Similarly, ellipses are also counted in the total length.

Usage: {{ 变量名|truncatewords:单词数量 }}

Example:Using the same text content:

<p>
    {{ "安企CMS 是一个基于 Go 语言开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。"|truncatewords:8 }}
</p>

Display result:AnQi CMS is an enterprise-level application developed based on the Go language...

It should be noted that for Chinese text,truncatewordsThe filter depends on spaces to identify "words", if a continuous Chinese text does not have spaces to separate it, it may treat it as a very long "word", leading to unsatisfactory truncation effects. In this case, usuallytruncatecharsWill be more suitable.

3.truncatechars_html: HTML safely truncates by character count

When processing rich text content containing HTML tags, use directly.truncatecharsortruncatewordsMay destroy HTML structure, causing the page to display abnormally.truncatechars_htmlThe filter is designed to solve this problem. It will intelligently retain and close all unclosed HTML tags while extracting content, ensuring that the extracted content is still valid HTML.

Special reminder:Any content that may contain HTML tags after extraction needs to be配合|safeThe filter informs the CMS that this content is safe, does not require HTML escaping, and thus allows the browser to render it correctly.

Usage: {{ 变量名|truncatechars_html:字符数量|safe }}

Example:Assuming we have a text that contains HTML tags:

Security CMSGreat! It providesFlexible content modeland powerful SEO tools.

"

<p>
    {{ "<p>安企CMS **很棒**!它提供了 <em>灵活的内容模型</em> 和强大的 SEO 工具。</p>"|truncatechars_html:25|safe }}
</p>

Display result:

Security CMSGreat! It providesFlexible content model...

4.truncatewords_html: HTML safely truncates by word count

withtruncatechars_htmlsimilar,truncatewords_htmlThe filter is performed by word count for HTML safe truncation. It also retains and closes HTML tags to prevent structural damage.

Usage: {{ 变量名|truncatewords_html:单词数量|safe }}

Example:Use the same text containing HTML tags:

<p>
    {{ "<p>安企CMS **很棒**!它提供了 <em>灵活的内容模型</em> 和强大的 SEO 工具。</p>"|truncatewords_html:8|safe }}
</p>

Display result:

Security CMSGreat! It providesFlexible content modeland...

Actual application scenarios and code examples

In Anqi CMS templates, these filters can be widely used in various content modules, such as:

1. Summary display in article list

On article or product list pages, we usually need to display a brief summary of the content.

"twig {# Assuming you are iterating over a document list and want to extract the document description #} {% archiveList archives with type="page" limit="10" %}"}

{% for item in archives %}
<div class="article-item">
    <a href="{{item.Link}}">
        <h3 class="article-title">{{item.Title}}</h3>
    </a>
    <p class="article-description">
        {# 截取文档描述的前100个字符

Related articles

How to implement complex conditional judgment and content iteration display in templates using `if/else` and `for` loop tags?

AnQi CMS as an efficient and flexible content management system, its template design capability is the key to building a rich and varied website content.During the template creation process, flexibly using conditional judgment (`if/else`) and content iteration (`for` loop`) tags can help us achieve a more intelligent and dynamic content display, allowing the web page to present personalized layouts and information according to different situations.

2025-11-08

How to determine if a variable (such as the article title) exists or is empty in a template and display a custom default value?

It is crucial to ensure the integrity and user experience of the content in website management.Sometimes, due to missing content or unassigned variables, blank areas or error messages may appear on web pages, which undoubtedly affects the professionalism of the website.The template engine of AnQiCMS provides a flexible and powerful mechanism to help users elegantly handle these situations, ensuring robust presentation of page content even if variables do not exist or are empty.In AnQiCMS template design, we often encounter situations where we need to display a variable (such as article title, description, image URL, etc.)

2025-11-08

How can AnQi CMS achieve automatic image compression and conversion to WebP format to optimize page loading performance?

Website images are important elements to enhance the attractiveness of content, but if not handled properly, they may also become the 'culprits' that slow down the website loading speed.For website operators, optimizing image loading performance can not only improve user experience but also have a positive impact on search engine rankings (SEO).AnQi CMS is an efficient content management system that fully considers this point, providing users with convenient and powerful image optimization features, especially automatic compression and WebP format conversion, allowing the website to maintain image quality while having faster loading speed.###

2025-11-08

How to display a dynamic banner image on the homepage of a website and implement click-through?

Displaying dynamic banner images with click-through functionality on the website homepage is a common need to enhance the visual appeal and user interaction of the site.By utilizing the powerful functions and flexible template mechanism of AnQiCMS, we can easily achieve this goal.The entire process is mainly divided into two parts: background configuration and front-end template invocation. ### First Step: Configure Banner Image and Link To display a dynamic rotating Banner on the website homepage, you first need to upload the image and set the link in the AnQiCMS backend. Typically

2025-11-08

In the display of the `Content` field of the article, how can I manually control the rendering conversion from Markdown to HTML?

When managing website content in AnQi CMS, we often use Markdown's concise and efficient features to write articles.However, ensuring that this Markdown-formatted content is rendered correctly into attractive HTML on the front-end page can sometimes be a focus for operators.This article will delve into how Anqi CMS handles the Markdown content of the `Content` field of the article, and guide you on how to manually control this rendering conversion process in the template.

2025-11-08

How to retrieve and display the list of all related documents under the Tag detail page?

In content operation, tags (Tag) are an extremely important tool that can help us effectively organize content, improve the quality of internal links on the website, and ultimately improve the user's browsing experience and the search engine's crawling efficiency.By tagging articles, products, or other content with relevant tags, we can associate content with the same theme scattered across different categories, forming a closer knowledge network.

2025-11-08

How to use `Json-LD` tags to customize structured data for optimizing the rich text summary display of search engines?

When a search engine displays search results, in addition to simple titles and descriptions, it sometimes also shows images, ratings, prices, authors, and other rich information, which is called 'Rich Snippets'.These eye-catching summaries can effectively enhance the visibility of the website in search results, attract more clicks from users, and thus bring more high-quality traffic to the website.In order to obtain these rich text summaries in search engines, we need to provide search engines with a standardized data format that they can understand, which is called "structured data".Among many structured data formats

2025-11-08

How to call and display specific content or system configuration information from other sites in a multi-site management mode?

AnQiCMS's powerful multi-site management feature brings great convenience to users with multiple brands or sub-sites.It can not only help you manage different content sites uniformly, but also supports cross-site data sharing and resource integration.When you want to display content from other sites on a site, or call the system configuration information of other sites, AnQiCMS provides a simple and efficient mechanism to achieve this goal.In AnQiCMS, the core of implementing cross-site content or configuration information calls lies in the flexible use of template tags such as `siteId`

2025-11-08