How to use filters (such as `truncatechars`) in AnQiCMS templates to truncate long text content and display it friendly?

Calendar 👁️ 59

In website operation, how to efficiently display content while ensuring the page is neat and beautiful is a challenge that every operator needs to face.Especially when the title, summary, or comments of an article are too long, if not handled properly, it is easy to break the page layout and affect the user experience.Fortunately, AnQiCMS provides a powerful and flexible template filter function, among whichtruncatecharsThe filtering function, which can help us elegantly solve this problem.

Optimizing content display: why do we need to truncate text?

Imagine that your website's list page has many articles, and if the titles or summaries of each article are uneven in length, even some are particularly long, the entire page will look disorganized.Users find it hard to find the key points at a glance, and may also choose to leave due to visual fatigue.By truncating overly long text and adding an ellipsis at the end, we can achieve:

  1. Maintain layout consistency: Regardless of the length of the original content, the length displayed on the page is fixed, ensuring alignment of card, list, and other elements.
  2. Improve reading efficiencyUsers can quickly browse key information and then decide whether to click to view the details, reducing information overload.
  3. Beautify page visualUniform text blocks make the page look more professional and attractive.
  4. Space-savingIn mobile devices or narrow modules, reasonably truncating text can effectively utilize limited display space.

AnQiCMS's template system borrows the syntax of the Django template engine, making it very convenient for content operators to process and format data in templates. Filters are one of the very practical tools, which are used through the pipe character|Process the variable, the syntax is usually{{ 变量 | 过滤器名称 : 参数 }}.

truncatechars: A tool for extracting plain text

When we need to extract plain text content, such as article titles, phrase tags, or brief introductions without any HTML tags,truncatecharsThe filter is your preference. It will truncate according to the number of characters you specify, and it will automatically add an ellipsis ("...") at the end of the text, and the length of the ellipsis will be included in the total number of characters you set.

For example, you want the title of the article list to be no longer than 20 characters, you can use it in the template like this:

<a href="{{ item.Link }}">{{ item.Title|truncatechars:20 }}</a>

Ifitem.TitleThe original content is "AnQiCMS: A high-performance enterprise-level content management system based on Go language", processedtruncatechars:20After processing, it may be displayed as "AnQiCMS: A high-performance enterprise-level content management system based on Go language..." or "AnQiCMS: A high-performance enterprise-level content management based on Go language..." (The actual handling of UTF-8 characters in Go language, one Chinese character counts as one character, but the position of the cut may vary slightly).This will control the visual length on the page regardless of the length of the original title.

truncatechars_html: Intelligent extraction with HTML content

In actual operation, many contents such as article summaries or comments may contain bold, italic, links, and other HTML tags. If used directlytruncatecharsThese tags may be truncated, causing the page HTML structure to become chaotic, even displaying abnormalities.

At this time,truncatechars_htmlThe filter comes into play. It can not only extract text, but also intelligently recognize and retain the integrity of HTML tags, ensuring that the extracted content is still a valid HTML fragment.Pay attention to adding at the end of the filter chain when in use|safeTo tell AnQiCMS template engine that this is a safe HTML fragment and no additional escaping is required.

For example, do you want to display the article summary on the list page, and the summary may contain bold keywords:

<p>{{ item.Description|truncatechars_html:100|safe }}</p>

This code ensuresitem.DescriptionAfter being truncated to 100 characters (including an ellipsis), all untruncated HTML tags can be closed correctly without damaging the page structure.

Advanced choice: truncatewordsandtruncatewords_html

In addition to truncating by character count, AnQiCMS also provides a feature for truncating by word count, that istruncatewordsandtruncatewords_htmlfilter. Their working principle istruncatecharsSimilar, but the main difference is that they take 'word' as the unit of truncation.This is very useful for English websites, it can avoid words being cut off in the middle, making the reading experience more natural.

  • truncatewords:数量: used for plain text, truncating by word count.
  • truncatewords_html:数量|safeUsed to include HTML text, truncating by word count and retaining the HTML structure.

For example:

<p>{{ item.EnglishTitle|truncatewords:10 }}</p>
<div class="summary">{{ item.HtmlSummary|truncatewords_html:20|safe }}</div>

Practical scenarios and techniques

  1. List page summaryIn the article list, product list, or news module,truncatechars_htmlCan control the length of the description text well, keeping it neat.

    {% for archive in archives %}
    <div class="item-card">
        <h3><a href="{{ archive.Link }}">{{ archive.Title|truncatechars:30 }}</a></h3>
        <p>{{ archive.Description|truncatechars_html:80|safe }}</p>
        <a href="{{ archive.Link }}" class="read-more">阅读更多</a>
    </div>
    {% endfor %}
    
  2. Comment previewAt the places where comments summary needs to be displayed, such as in the user management backend or the latest comments display of a module, it can be used flexibly.

    {% commentList comments with archiveId=archive.Id type="list" limit="6" %}
        {% for item in comments %}
        <div>
            <span>{{ item.UserName|truncatechars:6 }}</span>
            <p>{{ item.Content|truncatechars_html:50|safe }}</p>
        </div>
        {% endfor %}
    {% endcommentList %}
    
  3. Combine condition judgment to implement 'View More'To provide a better user experience, we usually only display the ellipsis or 'Read More' link when the content is actually truncated.You can compare the length of the original text with the specified truncation length.

    {% set original_title = item.Title %}
    {% set truncated_title = original_title|truncatechars:30 %}
    <h3>
        {% if original_title|length > 30 %}
            {{ truncated_title }} <a href="{{ item.Link }}">查看更多</a>
        {% else %}
            {{ original_title }}
        {% endif %}
    </h3>
    

    This code first retrieves the original title, then determines if its length exceeds 30 characters.If it exceeds, display the truncated title with a 'Read more' link;Otherwise, directly display the original title, avoiding unnecessary ellipses and links.

Summary

In AnQiCMS, usetruncatechars/truncatechars_htmlAn effective text truncation filter, which is an effective means to optimize website content display and enhance user experience.They help you present information in a neat and unified way within a limited page space, while ensuring the clarity and readability of the content and the integrity of the HTML structure.Master these practical filters and it will make your website content management more intuitive, enhancing both the visual and functional aspects of the website.

Frequently Asked Questions (FAQ)

1. Why did I usetruncatechars_htmlAfter that, the page display may still be confused, or there may be unclosed tags?This may be because you forgot to add at the end of the filter chain,|safe.truncatechars_htmlThe filter will intelligently handle HTML tags, but the AnQiCMS template engine defaults to escaping all output to prevent XSS attacks. If you don't add|safe,truncatechars_htmlValid HTML tags (such as<p>/<a>) will be escaped into&lt;p&gt;/&lt;a&gt;etc., which may cause the browser to fail to recognize and correctly render. Make sure{{ 变量 | truncatechars_html:长度 | safe }}the syntax

2.truncatecharsandtruncatewordsWhat is the essential difference? How should I choose?The core difference lies in the units they calculate and truncate:

  • truncatecharsPress:characterTruncates (including Chinese), and adds an ellipsis at the end. It may truncate in the middle of a word.
  • truncatewordsPress:wordsTruncate and add an ellipsis at the end

Related articles

How to replace specific characters in a string in AnQiCMS, affecting the presentation of front-end content?

In website operation, we often encounter situations where we need to modify or adjust the content, which is not just about updating text.Sometimes, we need to replace a specific word on a website with a new expression, or update links in bulk, or even dynamically process certain characters during content presentation.AnQiCMS as an efficient content management system provides a variety of flexible mechanisms to handle string replacement, thereby finely controlling the presentation of front-end content.### Backend bulk replacement: The efficiency tool for global content updates Imagine that the website you operate uses a specific product name

2025-11-07

How to use the `archiveFilters` tag in AnQiCMS template to achieve complex content filtering display?

In AnQiCMS, we often need to display website content in various ways, such as by category, tag, or even by the specific attributes of the content.When faced with more complex content organization needs, such as on a product list page, where not only products need to be displayed but also need to be filtered according to custom properties such as "color", "size", "material", etc., the `archiveFilters` tag comes into full play, helping us easily achieve these complex content filtering and display.

2025-11-07

How to optimize the display link of category and tag pages by using custom URL aliases in AnQiCMS?

In website operation, the URL (Uniform Resource Locator) is not only the address of the content but also an important component of user experience and search engine optimization.A clear, concise URL that contains keywords, which can help users understand the page content faster and also improve the page ranking in search engines.AnQiCMS as an efficient content management system, provides powerful custom URL aliasing functionality, allowing users to flexibly optimize the display links of category and tag pages.### Understand the importance of URL optimization Before delving into the specific operations of AnQiCMS

2025-11-07

How to configure banner images and thumbnails for a single page in AnQiCMS to enrich its visual display?

Today, with the increasing richness of website content, relying solely on text to convey information is no longer enough.Visual elements, such as eye-catching banner images and expressive thumbnails, can attract visitors' attention at first glance and enhance the professionalism and user experience of the website.For AnQiCMS users, cleverly configuring these visual elements for single pages (such as "About Us", "Contact Us", or "Service Introduction", etc.) is a simple operation that can bring great benefits.AnQiCMS fully understands the importance of content display and provides an intuitive backend management interface and a flexible template calling mechanism

2025-11-07

How does AnQiCMS ensure that the front-end displayed content is UTF-8 encoded and avoids garbled characters?

In website operation, content encoding is a crucial link, which directly affects whether users can read the text on the page normally.If encoding is not unified, the appearance of乱码 not only will seriously affect the user experience, but may also lead to information transmission errors.For AnQiCMS, ensuring that the content displayed on the front end is UTF-8 encoded to avoid garbled text issues is a core consideration in its system design and content management.First, Anqi CMS has provided a solid foundation for UTF-8 encoding in its underlying technical architecture.

2025-11-07

How to enable WebP image format in AnQiCMS to improve image loading speed and display efficiency?

Enable WebP image format in AnQiCMS: Optimize loading speed and display efficiency In today's digital age, website loading speed is one of the key factors in user experience and search engine ranking.Images are an important part of a website's content, and their loading efficiency has a crucial impact on the overall performance of the page.If the image size is too large or the format efficiency is low, it will not only slow down the website loading speed, but also consume the valuable traffic of users, and even affect the performance of the website in search engines.

2025-11-07

How to correctly display the link and title of the previous/next document in AnQiCMS template?

How to elegantly display the link and title of the previous/next document in the AnQiCMS template?When browsing articles on a website, users often want to easily navigate to related content, whether it's going back to the previous one for a deeper understanding or continuing to read the next new content.This "Previous/Next" navigation feature not only significantly improves user experience and extends the time users spend on the website, but also benefits the internal link structure and SEO optimization of the website.

2025-11-07

How to display user details such as avatar and username in AnQiCMS templates?

In AnQiCMS, flexibly displaying users' detailed information in templates, such as avatars and usernames, is an important step to achieve personalization and enhance website interaction.AnQiCMS's powerful template engine provides an intuitive and efficient way to integrate these data. ### Understanding the Data Calling Mechanism of AnQiCMS Template AnQiCMS template system uses a syntax style similar to Django, which makes template writing both intuitive and powerful.The essence lies in using specific template tags to call back-end data.

2025-11-07