In website content management, we often encounter situations where we need to截取overlong text content to maintain the page layout's neatness and consistency, without disrupting its semantics or formatting.Whether it's an article summary, product introduction, or user review, appropriately controlling the length of the text and adding ellipses can greatly enhance the user experience.truncatecharsandtruncatewordsas well as their variants for handling HTML content, help us easily achieve this goal.

Elegantly extract plain text content:truncatecharsWithtruncatewords

When your content is plain text, you can truncate it based on the number of characters or words.

  1. Truncate by character:truncatecharsAs the name suggests,truncatecharsThe filter truncates text based on the number of characters you specify. It starts counting from the beginning of the text and truncates it once it reaches the specified length, automatically adding an ellipsis at the end....The ellipsis consists of three characters as well. Please note this.

    Example Usage:Assuming we have a piece of text{{ item.Description }}.

    {{ item.Description|truncatechars:30 }}
    

    Ifitem.DescriptionThe content is 'AnQi CMS is an enterprise-level content management system developed based on the Go language, with powerful functions and simple deployment.'Then the above code may output: 'AnQi CMS is an enterprise-level content management system developed based on the Go programming language...' (The actual character count may vary due to encoding, but the logic is to count characters).

  2. Cut by words:truncatewordswhiletruncatewordsThe filter focuses more on the integrity of words.It will split by words (separated by spaces), and when you specify how many words to take, it will retain the first few complete words and then add an ellipsis.This is especially useful for English content, as it prevents words from being cut in half and becoming difficult to read.

    Example Usage:

    {{ item.Title|truncatewords:10 }}
    

    Ifitem.TitleThe content is 'AnQiCMS is a Go-based enterprise content management system with powerful features and easy deployment.' Then the above code may output: 'AnQiCMS is a Go-based enterprise content management system…'

Process content containing HTML:truncatechars_htmlWithtruncatewords_html

If your content includes HTML tags (such as rich text content in article details), use directlytruncatecharsortruncatewordsMay cause page structure chaos as they truncate characters indiscriminately, possibly cutting HTML tags in half. To solve this problem, Anqi CMS thoughtfully providestruncatechars_htmlandtruncatewords_htmlFilter.

These filters will intelligently close HTML tags while extracting text, ensuring the page structure is not damaged.Similarly, they are also divided into character truncation and word truncation.

Important reminder:When using these filters to process HTML content, please be sure to add at the output time.|safeFilter. This is because the template engine defaults to escaping all outputs for security reasons (converting<Converted to&lt;etc.), if not added|safeYour HTML tags will be outputted as is instead of being parsed by the browser.

  1. Truncate HTML by character:truncatechars_html Example Usage:

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

    Ifitem.Contentcontent is<strong>这是一段加粗的文字,后面还有很多内容,可能会被截断。</strong><p>这是一个段落。</p>The code above might output something like: "This is bold text, followed by much more content, which may be truncated.… Such a result, and HTML tags will be correctly closed and rendered.

  2. Extract HTML by words:truncatewords_html Example Usage:

    {{ item.SummaryHtml|truncatewords_html:20|safe }}
    

    This filter is similar totruncatechars_htmlSimilar, but the unit of extraction becomes words while maintaining the integrity of the HTML structure.

Actual application scenarios

With these filters mastered, you can flexibly apply them in the AnQiCMS template and optimize the display of your website content:

  • Summary display on the article list page:Display article titles and a short description on the homepage, category page, or search results page, usingtruncatecharsortruncatechars_htmlKeep the layout neat.
  • Brief introduction on the product details page:For long product features or introductions, use the snippet filter for a quick preview.
  • SEO Meta Description Control:Even if the content editor has written a long description, you can ensure that the Meta Description length complies with search engine **practices** by using these filters at the template level.
  • Unified display of user comments or messages:Truncate the longer comments submitted by users and display the full content after clicking to improve page loading speed and aesthetics.

Using tips

  • Use wisely|safeFilter:When you are sure that the output content has been processed by AnQiCMS and does not contain malicious code, for text containing HTML, it is imperative to use|safeto render correctly.
  • The effect of cutting Chinese and English text varies:For Chinese content,truncatewordsthe entire sentence is treated as a 'word' (unless there are spaces), therefore usuallytruncatecharsIt will be more suitable for Chinese content with word count truncation requirements. English content can be chosen according to the actual situation.
  • Flexible adjustment of truncation length:Find the most suitable truncation length for your website design and user reading habits by repeatedly testing different lengths.
  • CombineifUsage of statement:You can use these filters more intelligently, for example, only truncate and display an ellipsis when the content actually exceeds the preset length, otherwise display it as is. This can avoid unnecessary ellipses.
    
    {% set max_length = 100 %}
    {% if item.Content|length > max_length %}
        {{ item.Content|truncatechars_html:max_length|safe }}
    {% else %}
        {{ item.Content|safe }}
    {% endif %}
    

Masteredtruncatechars/truncatewordsAnd its HTML variant, you can make your AnQiCMS website content present more professionally and friendly, whether it is plain text or rich media content, it can be presented to users in a **posture**.


Common Questions (FAQ)

Q1: Why do I have to add when slicing content that includes HTML?|safeFilter?A1: This is because AnQiCMS's template engine is designed to prevent cross-site scripting (XSS) and other security issues by default. This means it will convert all output variable content to HTML.<to&lt;,>to&gt;If you don't add it,|safeThe HTML tag itself will also be escaped, causing it not to be recognized and rendered by the browser, but to be displayed as plain text on the page.|safeThe filter informs the template engine that this part of the content is safe and does not need to be escaped; it can be output directly in HTML format.

Q2:truncatecharsandtruncatewordsAre the automatically added ellipses (•••) included in the calculation of the truncated length?...) calculated in?A2: Yes, they include the automatically added ellipses (•••) in the calculation....The three characters or a 'word' unit are counted within the total截取 length. For example, if you usetruncatechars:10Then the total length of the final text (including the ellipsis) will be 10 characters.

Q3: How will the filter handle it if the length I set for truncation is longer than the actual text content?A3: If the truncation length you set is greater than or equal to the actual length of the text content, the filter will output the complete text without adding an ellipsis.Only when the text content actually exceeds the length you set will the filter truncate and add an ellipsis.