How can I truncate a string or HTML content in AnqiCMS template and add an ellipsis to control the display length?

Calendar 👁️ 72

In website operation, the way content is displayed has a significant impact on user experience and the efficiency of information transmission.Whether it is the introduction of the article list, the summary of the product description, or other text content that needs to be previewed, reasonable control of the display length and the addition of an ellipsis can not only maintain the neatness and beauty of the page, but also guide users to click and view more details.AnqiCMS as an efficient and flexible content management system provides a variety of powerful template tags and filters, making the control of content length extremely simple and intelligent.

Why is it necessary to truncate content and add an ellipsis?

Imagine if every article in your website's article list were displayed in full, the page would become overly long, and it would be difficult for users to browse quickly. Proper content truncation can bring many benefits:

  • Improve page aesthetics:A uniform abstract length can make the page layout more regular and improve visual comfort.
  • Optimizing user experience: Users can quickly scan multiple pieces of information, get a general understanding of the content, and then decide whether to delve deeper.
  • Improve loading speed:Reduce the amount of text loaded on the page initially, especially important for users on mobile devices or with poor network conditions.
  • Beneficial for SEO:A clear summary can help search engines better understand the page content and avoid a large amount of repetitive or redundant content on the list page.

AnqiCMS provides a直观且功能强大的content extraction tool in the template layer, whether it is plain text or content with complex HTML structure, it can handle it easily.

AnqiCMS content extraction filter

The AnqiCMS template system (similar to the Django template engine) includes a series of practical filters, specifically designed for string truncation. The one most relevant to controlling display length istruncatechars/truncatewordsand its HTML friendly versiontruncatechars_htmlandtruncatewords_html.

1. Extracting plain text content:truncatecharsandtruncatewords

When you need to extract plain text content without HTML tags, these two filters are your best choice.

  • truncatechars:length(By character cut)This filter will cut the string according to the number of characters you specifylength. If the length of the original string exceedslength, the extra part will be truncated and an ellipsis will be added at the end.... Please note,lengthThe parameter includes the final ellipsis character.

    Example:Assumearticle.TitleIs “How to truncate a string in AnqiCMS template and add an ellipsis to control the display length?”

    <p>{{ article.Title|truncatechars:20 }}</p>
    

    Output effect: 如何在AnqiCMS模板中截取...

  • truncatewords:count(Word-wise truncation)This filter will sort by the number of wordscountTo extract a string. It will try to truncate at word boundaries, which is particularly useful when dealing with English content, as it avoids cutting off the middle of a word.Likewise, if the content is truncated, it will be added at the end......

    Example:Assumearticle.DescriptionIs “AnQiCMS is a powerful and flexible content management system designed for ease of use.”

    <p>{{ article.Description|truncatewords:8 }}</p>
    

    Output effect: AnQiCMS is a powerful and flexible content...

2. Handle content containing HTML tags:truncatechars_htmlandtruncatewords_html

In a website, many content fields, such as article text, product details, etc., usually contain rich HTML tags (such as<strong>/<em>/<a>/<img>etc.). Use directlytruncatecharsortruncatewordsExtracting such content may break the HTML structure and cause the page to display incorrectly.

To elegantly handle the extraction of HTML content, AnqiCMS providedtruncatechars_htmlandtruncatewords_htmlTwo intelligent filters. They can intelligently close incomplete HTML tags while extracting content, thus ensuring that the HTML structure after extraction remains intact.

Important reminder:When you use_htmlBe sure to add it at the end of the filter when processing HTML content|safeFilterThe AnqiCMS template system, for security reasons, defaults to HTML-encoding all output content. If not added|safeEven though_htmlThe filter correctly closes the tags, and the browser will also display these HTML tags as plain text instead of parsing them.

  • truncatechars_html:length(Extract characters and retain HTML structure)This filter is compatible withtruncatecharsSimilar, extract by character count, but it ensures that all truncated HTML tags are properly closed.

    Example:Assumearticle.ContentIs<strong>AnQiCMS</strong> 是一个<em>高效</em>、可定制的内容管理系统,致力于提供******解决方案。

    {% set intro_content = article.Content|truncatechars_html:30|safe %}
    <div>{{ intro_content }} <a href="{{ article.Link }}">阅读更多</a></div>
    

    Output effect: <strong>AnQiCMS</strong> 是一个<em>高效</em>、可定... <a href="...">阅读更多</a>

  • truncatewords_html:count(Extract words and retain HTML structure)This filter is compatible withtruncatewordsSimilar, extract by word count, and intelligently close HTML tags.

    Example:Assumearticle.ContentIs<strong>AnQiCMS</strong> is a <em>powerful</em>, customizable CMS solution.

    {% set intro_content = article.Content|truncatewords_html:5|safe %}
    <div>{{ intro_content }} <a href="{{ article.Link }}">Read More</a></div>
    

    Output effect: <strong>AnQiCMS</strong> is a <em>powerful</em>, customizable... <a href="...">Read More</a>

Practical Exercise: Applying Content Extraction in Templates

Now, let's combine the actual template tags of AnqiCMS and see how we can flexibly use these extraction functions in document lists and detail pages.

Scenario one: The article list page displays a concise summary

On the article list page, we usually want each article to display only the title and a brief description, and provide a "Read More" link.

<div class="article-list">
    {% archiveList articles with type="page" limit="10" %}
        {% for item in articles %}
        <article class="article-item">
            <h2><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
            <div class="article-meta">
                <span>发布日期: {{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                <span>浏览量: {{ item.Views }}</span>
            </div>
            <div class="article-summary">
                {# 截取纯文本描述,并添加阅读更多链接 #}
                <p>{{ item.Description|truncatechars:150 }} <a href="{{ item.Link }}">阅读更多</a></p>
            </div>
        </article>
        {% empty %}
        <p>暂时没有文章内容。</p>
        {% endfor %}
    {% endarchiveList %}

    {# 分页导航,如果需要的话 #}
    {% pagination pages with show="5" %}
        {# 分页链接代码略 #}
    {% endpagination %}
</div>

In this example, we usearchiveListTag to get the list of articles, then extract from each article'sDescriptionField usagetruncatechars:150Ensure the consistency of the abstract length by cutting.

Scenario two: The 'expand/collapse' or first load part of the document detail page content

Sometimes, we may wish to display only a part of the content on the article detail page when it is first loaded, and then provide a button for the user to click to view the full content, or to only display a part of the formatted content in some special modules.

{% archiveDetail currentArticle %}
    <div class="article-detail">
        <h1>{{ currentArticle.Title }}</h1>
        <div class="article-content">
            {# 截取包含HTML的内容,注意使用 |safe 过滤器 #}
            {% set fullContent = currentArticle.Content %}
            {% set truncatedHtmlContent = fullContent|truncatechars_html:500|safe %}

            <div id="display-content">
                {{ truncatedHtmlContent }}
                {% if fullContent|length > 500 %}
                    <a href="javascript:void(0);" id="toggle-content">查看完整内容</a>
                {% endif %}
            </div>
            {# 实际操作中,可以使用JavaScript来切换完整内容和截取内容,这里仅为示意 #}
        </div>
    </div>
{% endarchiveDetail %}

Here, we usearchiveDetailRetrieve the detailed content of the current document and usetruncatechars_html:500YesContentfield for extraction. SinceContentfields usually contain HTML tags, we must use|safeA filter to ensure that HTML is parsed and displayed correctly.At the same time, we determine whether to display the 'View Full Content' button by judging the length of the original content and the length of the excerpt.

Some practical suggestions

  1. select filters based on actual requirements:If the content is confirmed to be plain text, usetruncatecharsortruncatewordsmore efficient. If the content may contain HTML,Make sureUsetruncatechars_htmlortruncatewords_html.
  2. do not forget|safe:the truncation filter for handling HTML content (_htmlAdd it after the)at the end,|safeFilter, otherwise your HTML tags will be output as is and not parsed by the browser.
  3. Consider truncating the length:

Related articles

How to determine whether a string, array, or object in AnqiCMS template contains a specific keyword and display content dynamically based on this?

In AnqiCMS, flexibly judging and dynamically displaying information based on content is the key to improving website user experience and SEO effects.Imagine that your website can automatically display related purchase links based on whether an article mentions a specific product; or recommend different sidebar content based on the category the user is in.This not only makes your website smarter, but also greatly improves the efficiency of content operation.The AnqiCMS template engine provides powerful features to help you easily implement these dynamic logic.

2025-11-09

How to display detailed information of image resources on the front page, such as file name, size, and image address?

When using AnQiCMS to manage website content, images are undoubtedly an important element in enhancing page attractiveness.We often need to display not only the image itself on the front-end page, but also further details about the image, such as their filenames, sizes, and storage addresses.This is very helpful for visitors to understand the background of the image, to reference the content, or to manage and download the image.

2025-11-09

How to display specific content or member permission prompts for different user groups on the front page of Anqi CMS?

In website operation, providing differentiated content or services for different user groups is an important strategy to enhance user experience and achieve content monetization.AnQiCMS (AnQiCMS) understands this need, built-in powerful user group management and VIP system, allowing you to easily implement personalized content display and permission control on the front page. ### Flexible User Groups and Permission System One of the core strengths of Anqi CMS is its flexible user group and VIP system.In the background, you can create multiple user groups, such as "Regular User", "Registered Member", "VIP Member"

2025-11-09

How to batch regenerate the thumbnails of AnqiCMS to adapt to the new display size requirements of the front page?

The display effect of image materials is crucial during website operation.Sometimes, due to website template updates, design style adjustments, or considerations for optimizing performance, the front-end page of the website may require new display sizes for image thumbnails.In this case, how can a large number of images uploaded to AnqiCMS (AnqiCMS) be generated into appropriate thumbnails according to new size requirements, rather than manually processing one by one, which has become a concern for many users.AnqiCMS fully considers the actual needs of content operators and built-in convenient thumbnail batch processing function

2025-11-09

How to automatically parse a URL string into a clickable a tag in AnqiCMS template for convenient browsing?

When operating a website, we often add some URLs in articles, product descriptions, or single-page content, which may be recommended external resources or references to other content within the site.But if these URLs are just displayed in plain text, users will have to copy and paste to access them, which is inconvenient and also affects the reading experience.AnqiCMS has fully considered this point and provided us with a very convenient way to automatically convert plain text URLs in the content into clickable links, greatly enhancing the convenience of user browsing and the professionalism of the website.

2025-11-09

How to display traffic or crawler access data charts on the front end of AnqiCMS's background data statistics function?

Understanding website traffic and user behavior is crucial for operators.AnqiCMS as an efficient enterprise-level content management system provides detailed data statistics and crawling monitoring functions in the background.This data can not only help us analyze the performance of the website and optimize the content strategy, but also has the potential to provide more intuitive information to users or visitors in specific scenarios through the display of charts on the front end.

2025-11-09

How can you dynamically obtain and display the current year or other time information in the AnqiCMS template?

In website operation, we often need to dynamically display the current year, date, or time on the page, such as the copyright information in the footer, the publication or update time of articles, etc.This information, if manually updated, is not only time-consuming and labor-intensive, but also prone to errors.Fortunately, AnqiCMS provides a concise and efficient method for you to easily implement the acquisition and display of these dynamic time information in the template.### Dynamically retrieve and display the current year or other time information In the AnqiCMS template, to retrieve and display the current year or any format of the current time, we can use the built-in

2025-11-09

How can AnqiCMS efficiently display the latest published article list on the homepage?

How can Anqi CMS efficiently display the latest published article list on the homepage?In website operation, the homepage as the first stop for user access, the activity of content updates often determines whether users are willing to stay and delve deeper into browsing.Especially for content-driven websites or corporate blogs, the homepage can dynamically display the latest list of published articles, not only presenting fresh content to visitors in the first place but also a key factor in improving user experience and search engine friendliness.So, how do we achieve this goal efficiently in AnQiCMS (AnQiCMS)?

2025-11-09