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