In website content operation, the article summary is like a business card of the article, it can catch the reader's attention at the first time, helping them quickly understand the main theme of the article, thereby deciding whether to delve deeper into reading.A well-designed abstract can not only enhance user experience, but also greatly benefit search engine optimization (SEO).However, facing the vast amount of articles, how to ensure that the summary is both accurate and comprehensive, and can flexibly adapt to articles of different lengths, avoiding being too long or too short, is a challenge faced by many operators.
AnQiCMS, as an efficient and flexible content management system, provides powerful template functions.By taking advantage of Django's template syntax and rich built-in filters, we can easily implement the need to dynamically adjust the length of the summary based on the number of words in the article, making the summary show unprecedented intelligence and adaptability.
The default mechanism of summary and the demand for dynamic adjustment
In the AnQiCMS document model, each article usually has a 'Document Description' field.If the operations personnel manually fill in the summary, the system will prioritize displaying this content.In practice, it may be due to the large number of articles, time constraints, or content updates that the 'document summary' is empty or uneven in length.At this time, AnQiCMS will default to extracting a part from the article's 'Document Content' (Content) as a summary.
However, this default truncation is often of fixed length, lacking flexibility.A concise and compact article may lack information if it is cut too short;And a long, rambling article, if only a fixed length is taken, may not fully demonstrate its key points.At this point, 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, obtain the full content of the article, then calculate the number of characters or words, and set different summary extraction length thresholds according to 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:
archiveDetailTagUsed to get the detailed information of the article, especially the complete "document content" (Content).wordcountFilter: Used to calculate the word count of article content (mainly applicable to English content).lengthFilter: Used to calculate the character count of article content (applicable to Chinese or other non-word separated languages).truncatewords_htmlortruncatechars_htmlFilter: Safely truncate content containing HTML tags based on word or character count and automatically add an ellipsis.{% if %}and{% set %}Tag: 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 the AnQiCMS template: If the article has a preset 'document summary', it will be displayed first;If not, extract from the 'document content'. If the content of the article exceeds 200 words, extract the first 100 words as a summary;If the number of words is between 100 and 200, extract 70 words;If less than 100 words, then cut the entire content.
Step one: Obtain the article content and preset summary
In the article detail page (for examplearchive/detail.htmlOr in the loop of the article list page, we can accessarchivefields directly from the object.
{# 尝试获取预设的Description #}
{% set summary = archive.Description %}
If it is in the loop of the article list page,archiveThe variable usually includes the "document description" (Description).But the complete "document content" (Content) is usually not preloaded in list data because it may be very large.So when needed, we need to usearchiveDetailtags to obtain.
{# 如果要获取完整的文章内容,通常需要像这样通过archiveDetail标签获取 #}
{% archiveDetail fullContent with name="Content" id=archive.Id %}
Step two: Calculate the word/character count of the article
Assuming we have already passedarchiveDetailThe tag assigns the complete HTML content of the article tofullContentthe variable. Now we need to calculate the word count or character count.
For English content separated by spaces, usewordcountThe filter is more intuitive:
{% set wordCount = fullContent|wordcount %}
For Chinese and other non-space-separated languages, or when accuracy to the character count is required (including punctuation and Chinese characters), uselengthFilter:
{% set charCount = fullContent|length %}
It is worth noting that,wordcountandlengththe filter calculatesPlain textthe word or character count. IffullContentContains HTML tags, these tags will also be counted. If you want to calculate the number of words/characters in 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 the abstract and output safely
In AnQiCMS, there is a string extractiontruncatewords(split by words) andtruncatechars(Character truncation) Filter. When the content contains HTML tags, in order to avoid truncation causing damage to the HTML structure, we should usetruncatewords_htmlortruncatechars_html. These with_htmlThe suffix filter intelligently handles HTML tags, ensuring that the truncated code remains valid.
At the same time, since the extracted content may still contain HTML, it is necessary to usesafea filter to prevent HTML from being escaped and unable to be displayed normally.
{% 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
Integrating the above steps into the template allows us to build a smart and flexible summary display module. Here is a sample code snippet that can be placed in the corresponding position in an article list or detail page:
`twig {# Assuming we are in a loop, item represents the current article object #} {# Or on a detail page, directly using the archive object #} {% set article = item %} {# On the list page it might be called item, on the detail page it might be archive #}
{% set displaySummary = article.Description %} {# Use the preset document summary first #}
{% if not displaySummary or length of displaySummary is less than 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