How to truncate the text or HTML content that is too long in the template and add an ellipsis to keep the page tidy?

Calendar 👁️ 82

It is crucial to maintain the neat and consistent layout of page content in website operation.Especially when it comes to displaying abstracts, product descriptions, or news headlines, the length of the original content is often inconsistent, which can easily lead to page layout errors and affect the user's reading experience.AnQiCMS provides very practical template filters that can help us easily truncate long texts or HTML content, and automatically add ellipses to keep the page elegant.

Understanding the importance of text truncation

Imagine a list of articles where some abstracts are very short and others are several hundred words long.If these summaries are not processed uniformly, the short summary area may appear hollow, and the long summary may burst the layout, even causing content overflow.This not only makes the page look unprofessional, but also makes it difficult for users to quickly browse information.Therefore, whether the content is plain text or contains various style tags of HTML, we need an intelligent way to control its display length, and use an ellipsis to indicate that the user's content has not yet ended.

Text truncation tool in AnQiCMS

The AnQiCMS template system (similar to the Django template engine) is built-in with a variety of filters that can help us complete this task. ForPlain text contenttruncation, we usually usetruncatecharsandtruncatewordsThese two filters.

  • truncatechars: This filter will sort according tocharacterThe number of characters to truncate the text. For example, if you want to display only the first 50 characters of a text and add an ellipsis at the end, you can use it like this:

    {{ item.Title|truncatechars:50 }}
    

    It will truncate the original content to the specified number of characters, including the ellipsis. If the length of the original content is less than or equal to the specified number of characters, no ellipsis will be added, nor will it be truncated.

  • truncatewordsIf you prefer to truncate text bywordsnumber (this is more common in English text),truncatewordsThe filter would be a better choice. It would try to truncate at the word boundaries to avoid splitting words abruptly.

    {{ item.Description|truncatewords:15 }}
    

    This code will truncate the description to the first 15 words and similarly handle the ellipsis.

Process content that contains HTML.

When the content to be truncated itself contains HTML tags (such as bold, italic, links, etc.), use it directlytruncatecharsortruncatewordsIt may damage the HTML structure, causing the page to display abnormally, for example, with unclosed tags. AnQiCMS fully considers this point and provides a special filter for processing HTML content:truncatechars_htmlandtruncatewords_html.

  • truncatechars_htmlThis filter is withtruncatecharsSimilar, but it will intelligently identify and retain the integrity of HTML tags.Even if truncation occurs within the tag, it will try to close the tag correctly, ensuring that the output HTML is valid.

    {{ archive.Content|truncatechars_html:100|safe }}
    

    Here, we givearchive.Contentthetruncatechars_htmlFilter, truncate content to 100 characters (including an ellipsis), while maintaining the integrity of the HTML structure. Please note that after truncating the HTML content, to ensure that the browser correctly parses HTML rather than displaying it as plain text, we also need to use it immediately after.|safefilter.|safeTell the template engine that this content is safe and does not require HTML encoding.

  • truncatewords_html: Similarly, if you need to truncate content containing HTML by word and want to preserve the integrity of the HTML structure, you should usetruncatewords_html.

    {{ product.RichDescription|truncatewords_html:30|safe }}
    

    This will truncate the rich text description of the product to 30 words and safely handle HTML tags.

Actual application scenarios and operation suggestions

In the AnQiCMS template files, these filters are usually associated witharchiveListorpageListThe content list tags are used in combination. For example, on an article list page, you may need to display the title and a brief summary of each article:

{% archiveList articles with type="page" limit="10" %}
    {% for item in articles %}
    <div class="article-item">
        <h3><a href="{{ item.Link }}">{{ item.Title|truncatechars:40 }}</a></h3>
        <div class="summary">
            {{ item.Description|truncatechars_html:80|safe }}
        </div>
        <a href="{{ item.Link }}" class="read-more">阅读更多</a>
    </div>
    {% empty %}
    <p>暂时没有文章发布。</p>
    {% endfor %}
{% endarchiveList %}

In this code block:

  • item.TitleIt is usually plain text, we usetruncatechars:40Truncate the title.
  • item.DescriptionIt may be rich text, to avoid destroying the internal HTML format, we chosetruncatechars_html:80, and added|safeTo ensure that HTML tags are rendered correctly.

By flexibly using these filters, we can accurately control the display length based on the specific design and content type of the page, effectively enhancing the visual cleanliness and user experience of the website.


Frequently Asked Questions (FAQ)

  1. Ask: Can the ellipsis after truncation be customized? For example, can it be changed to “… [Read more]”?

    • Answer: AnQiCMS built-intruncateThe series filter currently uses an ellipsis "…" by default and cannot be modified directly through parameters. If you need more complex prompt text, you may need to combineifDetermine the length of the content, then manually truncate the string and concatenate a custom prompt.
  2. Question: If my content is short and does not reach the truncation length, will the ellipsis still be displayed?

    • Answer: No.truncateSeries filters (including_htmlVersions are all designed not to truncate or add an ellipsis when the length of the original content is less than or equal to the specified truncation length.They are only added when the content is actually truncated.
  3. Ask: When I usetruncatechars_htmlafter, will the attributes inside the HTML tags (such as the image'saltattributes) be affected?

    • Answer:truncatechars_htmlandtruncatewords_htmlThe filter is designed to preserve the integrity and attributes of HTML tags as much as possible.It mainly focuses on content truncation and the correct closure of tags, usually does not actively modify the attribute values inside the tags.If the truncation point happens to be in the middle of an attribute value, then that attribute value may be truncated, so you need to weigh the truncation length accordingly.

Related articles

How to safely display user-submitted HTML content or JS code in a template to prevent XSS attacks?

In website operation, we often need to handle various types of content submitted by users, such as comments, messages, article submissions, etc.This content may contain HTML tags and even JavaScript code. If displayed directly on a webpage, it may introduce cross-site scripting attacks (XSS), posing a security risk to the website.AnQiCMS was designed with comprehensive consideration of content security and provides corresponding mechanisms at the template level to help us effectively prevent such risks.AnQi CMS uses a template engine syntax similar to Django

2025-11-08

Does AnQi CMS support direct arithmetic operations on strings or numbers within templates to affect display?

When building a website, we often need to handle various data, not just simply display it.For example, we may need to calculate the total price of goods, inventory surplus, or dynamically adjust the style of elements based on numerical size.These scenarios naturally lead to a core question: Does Anqi CMS support direct arithmetic operations on strings or numbers in templates, thereby flexibly affecting the display of content?The answer is affirmative. The AnQi CMS template engine cleverly adopts many advantages of the Django template, including direct support for arithmetic operations.

2025-11-08

How to use the structured data (JSON-LD) feature of Anqi CMS to enhance the search engine results display?

In today's highly competitive online environment, making a website's content stand out in search engine results pages (SERP) and attract more target users is the goal of every website operator.In addition to keyword optimization, high-quality content, and a good user experience, using structured data (JSON-LD) to "tell" search engines exactly what your content is becoming a key factor in improving website visibility and obtaining rich search results (Rich Snippets).

2025-11-08

How to define and display different banner images for different parts of the website in AnQiCMS?

In website operation, banner images are important visual elements that attract visitor attention and convey key information.They can not only enhance the overall aesthetics of the website, but also guide users to browse specific content or participate in promotional activities.AnQiCMS provides a flexible mechanism that allows you to customize and display unique Banner images for different parts of the website, such as the homepage, various thematic category pages, or independent content pages, thereby achieving more refined visual marketing.

2025-11-08

How to automatically convert a plain text URL into a clickable hyperlink in content display?

It is crucial to provide users with a smooth and convenient browsing experience in website operation.When our articles, pages, or product descriptions contain URLs in plain text form, if users need to manually copy and paste to access them, it will undoubtedly greatly reduce their user experience.AnQi CMS is well-versed in this, providing a simple and efficient method to automatically convert these plain text URLs into clickable hyperlinks, thereby bringing the content to life.### Let plain text URLs automatically come alive: The hyperlink conversion technique in Anqi CMS Imagine that

2025-11-08

How to define temporary variables in AnQiCMS templates to control display according to requirements?

In website operation and content management, we often need to flexibly display content based on specific conditions, or temporarily process and store some data at a certain stage of the template.AnQiCMS provides a powerful and easy-to-use template engine, which draws on the syntax of Django templates, allowing us to conveniently define and use temporary variables, thereby achieving fine-grained control over page content.AnQiCMS template files use the `.html` suffix and support Django template engine tag syntax.

2025-11-08

How to display the current year or a custom formatted datetime in the template?

In website operation and content management, displaying accurate date and time is a basic and important requirement.Whether it is the copyright year in the footer, the publication or update date of the article, or the countdown of a specific event, flexible control of the date and time format can greatly enhance the user experience and professionalism of the website.In AnQiCMS, you can easily implement the display of the current year or a custom date and time format using several simple and practical methods.--- ### One: Display the current system year or date and time: Use `{% now %}`

2025-11-08

How to use the AnQiCMS random text generation feature to fill placeholder content during the development stage?

In the process of website project development, we often face a common challenge: how to effectively build and test the layout and style of a website in the absence of actual content?From design prototypes to frontend development, filling in real content is time-consuming and impractical, and simple placeholder text is difficult to simulate the visual effects of real content.

2025-11-08