How to effectively display content in website operation while ensuring the page is neat and beautiful is a challenge that every operator needs to face.Especially when the text content of the article title, summary, or comments is too long, if not handled properly, it is easy to break the page layout and affect the user experience.truncatecharsEnglish translation: The filtering function 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. If the titles or summaries of each article are of different lengths, some even particularly long, the entire page will look disorganized.It is difficult for users to find the key points at a glance, and they may also choose to leave due to visual fatigue.

  1. Maintain layout consistency:No matter how long the original content is, the length displayed on the page is fixed, ensuring alignment of card, list elements, etc.
  2. Enhance reading efficiency:Users can quickly browse key information and decide whether to click to view details, reducing information overload.
  3. Enhance page visuals:Uniform text blocks make the page look more professional and attractive.
  4. Save spaceIn mobile devices or narrow modules, properly truncating text can effectively utilize limited display space.

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

truncatecharsA powerful 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 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", aftertruncatechars:20

truncatechars_html: Smart 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 directly,truncatecharsThese tags may be truncated, causing the page HTML structure to be confused, even displaying abnormal.

This is,truncatechars_html|safeTo tell AnQiCMS template engine that this is a safe HTML fragment and no additional escaping is required.

For example, 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 will ensureitem.DescriptionAfter being truncated to 100 characters (including ellipsis), all untruncated HTML tags can be correctly closed without damaging the page structure.

Advanced options:truncatewordsandtruncatewords_html

AnQiCMS also provides a feature to truncate by word count, that is,truncatewordsandtruncatewords_htmlfilter. Their working principles aretruncatecharsSimilar, but the main difference is that they take 'word' as the unit of segmentation.This is very useful for English websites, as 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:数量|safeEnglish for: Used to include HTML text, truncated by word count while retaining HTML structure.

For example:

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

Practical scenarios and skills

  1. List page summary: In article lists, product lists, or news modules,truncatechars_htmlCan control the length of the description text well, maintaining neatness.

    {% 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 previewIn places where it is needed to display comment summaries, 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 conditional judgment to implement 'view more'To provide a better user experience, we usually only display the ellipsis “…” or the link “View More” when the content is actually truncated.You can compare the length of the original text with the set 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 and then determines if its length exceeds 30 characters.If over, display the truncated title along with a 'View More' link; otherwise, display the original title directly, avoiding unnecessary ellipses and links.

Summary

In AnQiCMS, usingtruncatechars/truncatechars_htmlEnglish text truncation filter, an effective means to optimize website content display and enhance user experience.They help you present information in a tidy and unified way within 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, elevating the visual and functional aspects of your website to a new level.

Common Questions (FAQ)

1. Why did I usetruncatechars_htmlAfter that, the page is still confused, or some tags are not closed?This situation may occur if you forget to add it 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 do not add|safe,truncatechars_htmlGenerated valid HTML tags (such as<p>/<a>) will also be escaped as&lt;p&gt;/&lt;a&gt;, causing browsers to fail to recognize and render them correctly. Make sure{{ 变量 | truncatechars_html:长度 | safe }}is written correctly.

2.truncatecharsandtruncatewordsWhat is the essential difference? How should I choose?The core difference lies in the different units they use for calculation and truncation:

  • truncatechars: ByCharacterAuto-truncate text (including Chinese) and add an ellipsis at the end. It may truncate in the middle of a word.
  • truncatewords: BywordsAuto-truncate text and add an ellipsis at the end.