How to truncate a long string and display an ellipsis in AnQi CMS templates?

Calendar 👁️ 66

The flexibility of content display is crucial in the template creation process of AnQi CMS.When we need to display a long text within a limited space, such as an article summary, product description, or brief introduction, truncating the string with an ellipsis is a common optimization method that can effectively maintain the page layout and guide users to click to view the full content.The AnQi CMS is developed based on Go language, its template engine syntax is similar to Django, and it provides powerful filter (filters) functions to easily achieve this requirement.

Skillfully use filters to elegantly truncate strings

In AnqiCMS templates, the core tool for string truncation is the "filter". The filter can perform various transformations and formatting on variables, syntax is concise, usually with a vertical line (|) Connected to the variable name and can take parameters. AnqiCMS provides various practical filters for truncating long strings, which can truncate based on the number of characters or words and intelligently add ellipses.

1. For truncating plain text content:truncatecharsandtruncatewords

When you need to handle plain text content without any HTML tags, you can use:truncatecharsandtruncatewordsfilter.

  • truncatechars(Truncated by character count):This filter will truncate the string based on the number of characters you specify. It is worth noting that the truncated length includes the ellipsis added at the end....For example, if you specify truncation to 50 characters, then the actual content will occupy 47 characters, followed by 3 ellipses.

    <p>{{ item.Description|truncatechars:50 }}</p>
    

    This code will convertitem.DescriptionTruncate text to a maximum of 50 characters (including ellipsis), ensure that the display does not exceed the expected length regardless of the original description, and maintain a uniform layout.

  • truncatewords(Truncated by word count):If you want to truncate while maintaining the integrity of the word, rather than breaking in the middle of a word, thentruncatewordsIs a better choice. It will count and retain the specified number of complete words, and then add an ellipsis.

    <h3>{{ item.Title|truncatewords:10 }}</h3>
    

    This will ensureitem.TitleDisplay up to 10 words and add an ellipsis at the end to avoid a harsh reading experience.

2. Truncation for rich text content:truncatechars_htmlandtruncatewords_html

In website operation, many contents, such as the summary of article details, may contain bold, links, images, and other HTML tags. If used directly,truncatecharsortruncatewords, may destroy the HTML structure, causing the page to display abnormally, for example, the tag is not closed.In order to solve this problem, AnqiCMS provides a dedicated truncation filter for handling HTML content.

  • truncatechars_html(Truncate HTML by character count and maintain structure):This filter function is withtruncatecharsIt is similar, but it will intelligently identify and maintain the integrity of HTML tags.Even if truncation occurs within the tag, it will ensure that all open HTML tags are closed correctly, thereby generating a valid HTML fragment.

    <div class="summary">{{ archive.Content|truncatechars_html:120|safe }}</div>
    

    When you start fromarchive.ContentSuch a rich text field can be summarized using this filter to ensure that the truncated HTML code is valid and does not break the page style. Note that in order for the HTML content to be rendered correctly rather than escaped as plain text, it must be followed by|safefilter.

  • truncatewords_html(Truncate HTML by word count and maintain structure):withtruncatewordsSimilar, but applicable to HTML content. It truncates by word count and maintains the integrity of HTML tags as well.

    <div class="excerpt">{{ archive.Content|truncatewords_html:30|safe }}</div>
    

    This filter is very suitable for generating a concise summary containing a few words from rich text content, while ensuring the integrity of its HTML structure. Similarly, don't forget to use|safe.

Practice Application and **Practice

In practical applications, the choice of truncation filter depends on your specific needs and content type:

  • Plain text description: For articles or productsDescriptionfield is recommended to usetruncatecharsbecause it can accurately control the length of the displayed characters, which is very suitable for fixed-width layouts.
  • short title or label:truncatewordsWhen it is necessary to maintain the integrity of words but worry about the length of the title, it can be used, although the actual usage scenario is relatively rare because the title is usually limited in length.
  • Rich text summaryWhen extracting part of the content from an articleContentto serve as a summary,truncatechars_htmlortruncatewords_htmlthey are indispensable. They can perfectly balance the length of the content and the integrity of the HTML structure.

Here are some tips:

  • Reasonably set the truncation length: A short truncation may lead to insufficient information, while a long truncation may lose aesthetic advantages. It is recommended to test from multiple perspectives according to your design and page layout to find the most suitable length.
  • Pair with "View More" linkThe purpose of truncation is to preview, which is usually accompanied by a link to view more or read the full content to provide a complete user experience.
  • Always use|safeWhen you go through_htmlWhen processing and outputting content that may contain HTML tags, be sure to add|safeTo avoid the default HTML entity escaping behavior of the template engine, ensure that the HTML code can be correctly parsed by the browser.

By flexibly using these truncation filters, you can easily manage the display of long strings in the AnqiCMS template, enhancing the overall beauty and user experience of the website page.


Frequently Asked Questions (FAQ)

Q1: Does the truncated length include an ellipsis?A1: Yes, when you usetruncatecharsortruncatechars_htmlwhen you specify the number of characters (for exampletruncatechars:50) it will include the final ellipsis (...The characters occupied. This means the actual number of characters displayed will be less than the specified value.

Q2: If my string is already short and does not exceed the truncation length, will the ellipsis still be displayed?A2: Will not. These truncation filters of AnqiCMS will only add ellipses when actual truncation occurs.If the length or word count of the original string does not exceed the truncation value you specify, it will display the string in full without adding an ellipsis.

Q3:|safeWhat is the role of a filter, and when do I need to use it?A3:|safeThe filter informs AnqiCMS's template engine that the string it processes is "safe" HTML code that does not require the default HTML entity escaping. When you display rich text content retrieved from the database (which may contain bold, links, and other HTML tags), or usetruncatechars_html/truncatewords_htmlWhen the filter processes HTML content, in order to ensure that the HTML tags are rendered correctly by the browser rather than displayed as plain text, it is necessary to add to the output variable|safe.

Related articles

How to automatically add hyperlinks to URLs and email addresses in article content of AnQi CMS?

In content management and website operations, automatically converting URLs and email addresses in the text to clickable hyperlinks can greatly enhance user experience and optimize the internal link structure of the website to some extent.For AnQiCMS users, implementing this feature is not through simple backend settings, but through the specific "filter" provided by its powerful template engine.This design approach gives website owners great flexibility and control, allowing them to finely manage the generation of links according to the needs of different content areas.

2025-11-08

How to display multi-language switch links and the current language identifier in Anqi CMS?

In AnQi CMS, implementing multi-language switch links and current language identification is a very practical feature that can help your website easily face global users and enhance the internationalization level of your website.Aqicms provides intuitive and powerful template tags, allowing you to flexibly display these elements on the website front end. ### One, understand the multilingual capabilities of Anqicms Anqicms has considered the needs of multilingual sites from the very beginning and provides comprehensive multilingual content management support.This means you can create and manage independent content for different languages in the background, such as articles

2025-11-08

How to display a custom prompt message during the website shutdown maintenance of AnQi CMS?

During the operation of the website, we sometimes have to temporarily close the website for maintenance in order to upgrade the system, optimize data, or adjust functions.How to clearly and friendly convey this status to visitors, avoiding confusion or loss of users, is particularly important.Safe CMS provides a set of built-in solutions that allow you to easily customize the prompt information for your website during maintenance shutdown. ### Understanding the shutdown mechanism of AnQi CMS The shutdown feature of AnQi CMS is designed to be very intuitive and flexible.When you enable the closed site mode, the system will automatically intercept all access requests to the website content

2025-11-08

How to reference common code snippets (such as headers and footers) in Anqi CMS templates to unify page display?

It is crucial to maintain consistency in the display of web pages during website operations.A unified website appearance can not only enhance brand professionalism but also optimize user experience.AnqiCMS provides a powerful and flexible template mechanism, allowing us to efficiently manage common website elements such as headers and footers, thus avoiding repetitive code writing and ensuring the consistency of the entire site style.The AnqiCMS template system draws on the syntax of the Django template engine, with the core idea being that developers can define reusable code snippets and page skeletons

2025-11-08

How can AnQi CMS templates inherit parent templates and rewrite specific block content to customize display?

In Anqi CMS, the template system provides a powerful and flexible mechanism that allows users to efficiently customize the layout and content display of the website.Among them, "inheriting the parent template and rewriting specific block content" is a key function to achieve personalized design and maintain consistency with the overall style of the website. ### Core Concept: Say goodbye to repetition, embrace inheritance Imagine that the header, footer, sidebar, and other elements of a website are fixed and unchanged on almost every page. If there is no template inheritance mechanism, we may need to repeat this common code in each page template, which increases the difficulty of maintenance

2025-11-08

How can AnQi CMS use the 'time factor' feature to display future published content?

How to efficiently and strategically publish content in today's fast-paced content environment is a question that every content operator is thinking about.Maintain the consistency and foresight of content publication, which can not only enhance the user experience but also effectively promote brand communication and search engine optimization.AnQi CMS deeply understands this, and its 'Time Factor' feature was born for this very purpose, providing content creators and operation teams with a precise tool to control the timing of content release.## Precise Planning: The Foundation of Content Operation We have all faced such a situation: writing an精心 prepared article

2025-11-08

Does AnQi CMS provide an integrated JS statistics code calling tag for easy display on the page?

When using AnQiCMS, many users are concerned about how to conveniently integrate third-party JavaScript statistical codes into web pages, such as Baidu Statistics, Google Analytics, and so on.About this, AnQiCMS indeed provides built-in mechanisms and flexible template tags, allowing you to easily call and display these statistics codes on your website.### Using built-in JS code to call tags AnQiCMS to meet the needs of website operators to integrate third-party scripts

2025-11-08

How to display the current year or time in a specific format in AnQi CMS template?

In website operation, it is a common requirement to flexibly display the current year or format specific time, whether it is the automatic update of the year in the copyright statement or the clear display of the publication time on the article detail page.AnQiCMS provides two main ways to meet these needs, they are both simple to use and follow the elegant time handling of the Go language.### Method 1: Directly retrieve and display the current year or time (`{% now %}` tag) When you need to directly retrieve and display the current year or the current time down to the second in the template

2025-11-08