How to limit the maximum number of characters that `archive.Content` displays in the summary in the template?

Calendar 👁️ 62

How to effectively display content summaries in website operations, which can attract visitors to click and maintain page tidiness, is a common and important issue.For friends using AnQiCMS, we often need to extract the essence of the document content as a summary for display on list pages, search result pages, or related article recommendation modules.This article will introduce how to accurately control in AnQiCMS templatearchive.ContentThe maximum number of characters displayed in the abstract.

Understandingarchive.Contentwitharchive.DescriptionDifference

In AnQiCMS, you will come across two fields closely related to the article content:archive.Contentandarchive.Description.

  • archive.ContentThis usually refers to the complete content of a document. It may contain rich HTML tags (such as images, paragraphs, links, etc.), carrying all the information of the article.
  • archive.DescriptionThis field is designed to store a brief description or summary of the document. When you publish a document, if you do not manually fill in the document description, the AnQiCMS system will automatically extract fromarchive.ContentExtract the first 150 characters asarchive.Description.

In most cases, when you need to display article summaries on list pages, we strongly recommend using them firstarchive.Description. Because it is born for this purpose, the content is more concise, and it has a default truncation length. However, in some specific scenarios, for examplearchive.DescriptionNot filled in, or you want to start fromarchive.ContentTo obtain a summary of different lengths, we need to manually truncate it.

Use the template filter to limit the content length.

AnQiCMS's template engine supports Django-like syntax and provides powerful filter (Filters) functions to help us easily handle data, including string truncation. It is designed for content that includes HTML.archive.ContentField, we have several very practical filters to choose from.

1.truncatechars_html: Retain HTML structure and cut by character

This is the processingarchive.ContentThe most recommended method, as it can intelligently extract text while trying to maintain the integrity of HTML tags, avoiding page display anomalies caused by tag truncation.

Working Principle:truncatechars_htmlCalculates the specified number of characters (including any ellipses generated), and attempts to close any incomplete HTML tags when truncating, ensuring that the output HTML is valid.

Usage methodIn your template file, find the one you are displayingarchive.Contentand replace it with the following format:

{{ archive.Content|truncatechars_html:120|safe }}
  • archive.Content: The original document content you want to extract.
  • |truncatechars_html:120:truncatechars_htmlIs the name of the filter,120Is the maximum number of characters you want to display. Please note that this number includes the ellipsis that may appear at the end....Contains HTML tags,
  • |safe:This filter is crucial!due toarchive.ContentContains HTML tags,truncatechars_htmlThe result is still HTML. If you don't add|safeA filter, the template engine will default to escaping HTML tags (for example<p>Will become&lt;p&gt;This causes the page to directly display the HTML code instead of parsing the content.|safeExplicitly tell the template engine that this content is safe HTML and can be output directly.

Code exampleAssuming you are on a list page of articles (list.htmlorindex.html) display the summary of each article:

<div class="article-item">
    <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
    <div class="article-summary">
        {# 优先使用 Description 作为摘要 #}
        {% if item.Description %}
            <p>{{ item.Description }}</p>
        {% else %}
            {# 如果 Description 不存在,则截取 Content 的前120个字符作为摘要 #}
            <p>{{ item.Content|truncatechars_html:120|safe }}</p>
        {% endif %}
        <a href="{{ item.Link }}" class="read-more">阅读更多</a>
    </div>
</div>

2.truncatewords_htmlPreserve the HTML structure and cut by word

If you think splitting by words is more suitable for your summary display needs, you can usetruncatewords_html.

Working Principle: withtruncatechars_htmlSimilar, but it splits by words as well and also tries to close HTML tags.

Usage method:

{{ archive.Content|truncatewords_html:40|safe }}
  • 40This indicates the maximum number of words you wish to display.

Select suggestions:

  • truncatechars_htmlSuitable for scenarios with strict character limits for abstract length (e.g., to maintain page layout alignment).
  • truncatewords_htmlApplicable when you care more about the semantic integrity of the summary, hoping to end the summary with complete words rather than half-cuts.

3.truncatecharsandtruncatewords: For plain text content

If yourarchive.ContentEnsure that the field is plain text (without any HTML tags), or you have removed the HTML tags in some other way before capturing, then you can use these two simpler filters.They do not handle the closing of HTML tags.

Usage method:

{{ archive.Content|truncatechars:100 }} {# 截取100个字符 #}
{{ archive.Content|truncatewords:30 }} {# 截取30个单词 #}

Note: Due toarchive.ContentHTML usually contains, directly using these two filters may cause the HTML structure of the page to be damaged. Therefore, forarchive.Contentmust be given priority totruncatechars_htmlortruncatewords_html.

Summary of implementation steps

  1. determine the location of the summary displayFind the template file that needs to be displayed in your website summary, such as the article list page (archive/list.htmlorindex.html), search results page (search/index.html) and so on.
  2. Locate the content output tag: Find the variables used to output document content in this template file, usually{{ item.Content }}or{{ archive.Content }}.
  3. Apply the truncation filter: Choose according to your needs,truncatechars_htmlortruncatewords_htmlFilter and set the maximum number of characters or words. Also, don't forget to add|safefilter.
  4. Save and Test: Save the template file, refresh your website page, check if the summary display meets expectations, and whether the HTML structure is normal.

By using the above method, you can flexibly control the AnQiCMS template inarchive.Contentthe display length of the field, making your website content more beautiful and efficient.


Frequently Asked Questions (FAQ)

Q1: Why when usingtruncatechars_htmlAfter, my summary content still displayed the HTML code instead of the parsed effect? A1:This is likely because you forgot totruncatechars_htmlafter the filter|safeFilter. AnQiCMS's template engine defaults to escaping all output HTML content to prevent cross-site scripting attacks (XSS).|safeThe filter explicitly tells the engine that this content is confirmed safe HTML, which can be output and parsed as is without escaping.

Q2: Should I choose to truncate by character (truncatechars_html) or by word (truncatewords_html)? What is the difference? A2:It mainly depends on your design preference and semantic requirements.

  • Character-based cutting (truncatechars_html)When you need to display an abstract with strict control over the number of characters (for example, for a uniform layout) use it.The drawback is that it may truncate words, resulting in a slightly disjointed reading experience.
  • Cut by word (truncatewords_html)When you pay more attention to the semantic integrity of the summary, you hope that the sentence ends with a complete word.The actual number of characters may not be fixed and may exceed expectations sometimes.Both will have an ellipsis added after the truncation (...),and try to maintain the integrity of the HTML tag structure.

Q3: If I set the cut length, but the originalarchive.Contentcontent is shorter than this length, what will happen? A3:If the total length (or word count) of the original content is less than you

Related articles

How to judge the length of the article summary `archive.Description` to decide whether to display the 'Read More' link?

In website operation, the neatness of the content list page and the user experience are crucial.When the article summary is too long, it may not only occupy too much page space, affecting the overall layout beauty, but may also dilute the guiding role of the 'Read More' link.Therefore, deciding intelligently whether to display a "Read More" link based on the actual length of the article summary is an effective strategy to enhance the professionalism and user-friendliness of the website.AnQiCMS (AnQiCMS) provides powerful and flexible template functions, making it simple and efficient to meet this requirement.### Understand `archive

2025-11-08

How to get the character length of the article title `archive.Title` for content truncation display?

In website content display, controlling the length of article titles is a common requirement, especially in list pages, recommended positions, and other scenarios, where overly long titles may destroy the page layout and affect user experience.AnQiCMS provides powerful and flexible template tags and filters to help users easily obtain and truncate the display of article titles `archive.Title`. ### Article Title in AnQiCMS Template In the AnQiCMS template, when we handle article data, we usually go through

2025-11-08

How to implement the combination of document title and link display with the `combineId` and `combineFromId` parameters in the `archiveList` tag?

In website content operation, we often encounter scenarios where it is necessary to display the relevance between different contents, such as the "From A to B" in travel products, the "Comparison of Product A and Product B" on product detail pages, or the "Basic service with value-added service" in service solutions. Anqi CMS provides two very practical `archiveList` tag parameters - `combineId` and `combineFromId`, which can help us display the title and link of documents in a flexible and dynamic way, thereby enhancing the richness of content and user experience.

2025-11-08

How to retrieve and flexibly display custom parameter fields in the document model with the `archiveParams` tag?

When managing content in AnQi CMS, we often encounter situations where we need to add specific attributes for different types of content (such as articles, products).The 'Content Model' feature provided by AnQi CMS allows us to customize fields according to business requirements, greatly enhancing the flexibility and scalability of content.How can I elegantly and flexibly obtain and display these custom parameter fields in the website front-end template?The `archiveParams` tag is the key to solving this problem.### Understanding the Custom Parameters in the Document Model Diving deeper into

2025-11-08

How to check how many images are included in the group image `archive.Images` array on the article detail page?

It is crucial to manage the image display on the article detail page flexibly and accurately when building website content in AnQi CMS.Especially when we need to use multiple images to enrich the content of an article, the collage feature (usually corresponding to the `archive.Images` field) provides an efficient and convenient solution.In the operation, sometimes we need to understand how many images a specific article detail page contains, whether it is for page layout design, content statistics, or executing logic judgments under specific conditions.This article will elaborate on how to accurately check in AnQi CMS templates

2025-11-08

How to get the number of top-level menu items in the website navigation list `navList`?

In website content operation, the navigation menu is the first door for users to interact with the website content.AnQiCMS (AnQiCMS) provides a flexible `navList` tag to help us easily manage and display website navigation.Sometimes, in order to achieve a specific layout, style, or dynamic adjustment, we need to know the specific number of top-level navigation menu items on the website.This article will thoroughly introduce how to obtain the number of top-level menu items in the `navList` navigation list of AnQiCMS templates.### Understand `navList`

2025-11-08

How to judge if the length of the user comment content `comment.Content` exceeds the limit for front-end verification?

In website operation, the comment feature is an important part of user interaction.To maintain a good community environment and data quality, we usually limit the length of the comments submitted by users.Front-end validation plays a crucial role in this process, providing immediate feedback before submission to avoid failure due to content length, thereby enhancing user experience and reducing server load.How can we judge whether the length of the user comment content `comment.Content` exceeds the limit in the website built using AnQiCMS?

2025-11-08

How to get the total length of the document list `archives` being traversed in the `for` loop?

In AnQiCMS template development, we often need to traverse document lists, such as through the `archiveList` tag content.In such a `for` loop, understanding the total length of the current list is a very practical need, as it can help us implement some specific display logic, such as showing 'Article N of M' or determining if the list is empty.The AnQi CMS template engine adopts Django's syntax, providing a set of intuitive and powerful tags and filters to process data.To get `for`

2025-11-08