In website content operation, the article summary is like a business card of the article, which can catch the reader's attention at the first time and help them quickly understand the main theme of the article, thus deciding whether to read it in depth.An expertly designed summary can enhance user experience and be highly beneficial for search engine optimization (SEO).However, faced with a vast amount of articles, how to ensure that the summary is both accurate in summarizing the content and flexible to adapt to articles of different lengths, avoiding being too long or too short, is a challenge many operators face.
AnQiCMS, as an efficient and flexible content management system, provides powerful template functions.With its class-like Django template syntax and rich built-in filters, we can easily implement the need to dynamically adjust the summary length based on the number of words in the article, allowing the summary to show unprecedented intelligence and adaptability.
The default mechanism of summary and the need for dynamic adjustment.
In AnQiCMS's document model, each article usually has a 'Document Description' field.If the operator manually fills in the summary, the system will prioritize displaying this content.But in practice, it may be due to the large number of articles, time constraints, or content updates, resulting in the 'Document Summary' being empty or uneven in length.At this time, AnQiCMS will default to extracting a part of the article's 'Content' as a summary.
However, this default truncation is often of fixed length, lacking flexibility.An article that is concise and forceful may lack information if it is cut too short; on the other hand, a long and flowing article may fail to fully present its core points if it is only cut to a fixed length.This is when we need a mechanism that can dynamically adjust the length of the summary based on the actual 'weight' of the content of the article.
Core idea: Quantify content, flexible extraction.
The core of realizing dynamic abstracts lies in: first obtaining the full content of the article, then calculating its word count or number of words, and setting different abstract extraction length thresholds based on these quantitative indicators.AnQiCMS powerful template tags and filters provide us with the tools to implement this idea.
We will mainly utilize the following key elements:
archiveDetailtags:Used to obtain the detailed information of the article, especially the complete 'document content' (Content).wordcountFilter:用于计算文章内容的单词数量(主要适用于英文内容)。lengthFilter:用于计算文章内容的字符数量(适用于中文或其他非单词分隔的语言)。truncatewords_htmlortruncatechars_htmlFilter:According to the number of words or characters, safely truncate content containing HTML tags and automatically add ellipses.{% if %}and{% set %}tags:Used for logical judgment and variable assignment in templates.
Implementation steps
Below, we take a specific scenario as an example to demonstrate how to implement dynamic abstracts in AnQiCMS templates: if there is a preset 'Document Summary', it will be displayed first; if not, it will extract from the 'Document Content'.If the number of words in the article content exceeds 200, extract 100 words as a summary; if the number of words is between 100 and 200, extract 70 words; if fewer than 100 words, extract the entire content.
Step one: Retrieve the article content and preset summary
In the article detail page (for example)archive/detail.html)or in the article list page loop, we can access its fields directly.archiveDirectly access the fields of the object.
{# 尝试获取预设的Description #}
{% set summary = archive.Description %}
If it is in the article list page loop,archiveThe variable usually includes the "document summary" (Description) of the article.The complete "document content" (Content) is usually not preloaded in list data, as it may be very large.archiveDetailyou can get it by tag.
{# 如果要获取完整的文章内容,通常需要像这样通过archiveDetail标签获取 #}
{% archiveDetail fullContent with name="Content" id=archive.Id %}
步骤二:Calculate the word/character count of the article.
Suppose we have alreadyarchiveDetailThe tag assigns the complete HTML content of the article.fullContentNow we need to calculate the word count or character count.
For English content separated by spaces, usewordcounta more intuitive filter:
{% set wordCount = fullContent|wordcount %}
For languages such as Chinese that are not separated by spaces, or when the exact number of characters (including punctuation marks, Chinese characters, etc.) is required, uselengthFilter:
{% set charCount = fullContent|length %}
It is worth noting that,wordcountandlengthThe filter calculates isPlain textthe number of words or characters. IffullContentContains HTML tags, which are also counted. If you want to calculate the number of words/characters of plain text without being disturbed by HTML tags, you can first usestriptagsFilter to remove HTML tags:
{% set pureTextContent = fullContent|striptags %}
{% set pureWordCount = pureTextContent|wordcount %}
{% set pureCharCount = pureTextContent|length %}
Step three: dynamically extract abstract and safely output
In AnQiCMS, there are methods to extract strings:truncatewords(split by words) andtruncatecharsEnglish Extractor. When content contains HTML tags, in order to avoid truncation that may damage the HTML structure, we should usetruncatewords_htmlortruncatechars_html._htmlThe suffix filter will intelligently handle HTML tags, ensuring that the truncated code is still valid.
At the same time, since the extracted content may still contain HTML, the output needs to be formatted usingsafea filter to prevent HTML from being escaped and displayed abnormally.
{% set targetWords = 50 %} {# 默认截取单词数 #}
{% if pureWordCount > 200 %}
{% set targetWords = 100 %}
{% elif pureWordCount > 100 %}
{% set targetWords = 70 %}
{% endif %}
{# 动态截取摘要,保留HTML结构,并确保安全输出 #}
{% set dynamicSummary = fullContent|truncatewords_html:targetWords|safe %}
Step four: Integrate all logic into the template
Integrate the above steps into the template, and we can build an intelligent and flexible summary display module. Here is a sample code snippet that can be placed at the corresponding position in the article list or detail page:
`twig {# 假设我们正在一个循环中,item代表当前文章对象 #} {# 或者在详情页中,直接使用archive对象 #} {% set article = item %} {# 在列表页可能叫item,详情页可能直接是archive #}
{% set displaySummary = article.Description %} {# Use the predefined document summary first #}
{% if not displaySummary or displaySummary|length < 10 %} {# If the preset summary is empty or too short #}
{# 再次确认在循环中需要使用ID获取Content,在详情页可省略id参数 #}
{% archiveDetail fullContent with name="Content" id=article.Id %}
{% if fullContent %}
{# 先移除HTML标签,获取纯文本进行字数/单词数判断 #}
{% set pureTextContent = fullContent|striptags %}
{% set wordCount = pureTextContent|wordcount %} {# 假设主要处理英文,用wordcount #}
{# 如果是中文,更建议使用 charCount = pureTextContent|length #}
{% set targetLength = 120 %} {# 默认截取字符数,适用于混合或中文内容 #}
{% set truncationFilter = 'truncatechars_html' %} {# 默认使用字符截取,并保留HTML #}
{# 根据单词数量或字符数量调整截取长度 #}
{% if wordCount > 300 %}
{% set targetLength = 2