In the template development of AnQi CMS, flexibly handling text and HTML content is a daily operation. When we need to convert plain text content entered by users,linebreaksWhen converting a filter to an HTML structure with paragraphs and line breaks while also limiting its display length, a common problem will arise:linebreaksProcessed HTML content, can it be safely usedtruncatechars_htmlWhat about the truncation by the filter

The answer is affirmative, not only can it, but this is exactly whattruncatechars_htmlThe powerful design of the filter. Next, let's take a detailed look at the working mechanism of these two filters, as well as how they elegantly work together.

linebreaksFilter: Converts plain text into HTML structure

Firstly,linebreaksThe filter plays a very practical role in the Anqi CMS template. Its main function is to convert newline characters in plain text into HTML elements.\n)smartly converted to HTML paragraph tags (<p>)and newline tags<br/>).

Imagine, if the back-end editor enters multiple lines of text in the content field, separated by two newline characters between paragraphs, and simply uses a single newline character within paragraphs.If not processed and output directly, the front-end page may only display a long string of unformatted text.linebreaksAfter the filter intervenes, it will convert such plain text content, by convention, into easily readable HTML paragraph structures. Specifically:

  • Continuous two newline characters will be parsed as a new HTML paragraph, using<p>...</p>Package.
  • A single newline character will be converted to an HTML<br/>tag to implement line breaks within paragraphs.

For example, an input like this:

这是第一段内容。
这里有段内换行。

这是第二段内容。

AfterlinebreaksProcessed, the output will be approximately as follows in HTML:

<p>这是第一段内容。<br/>这里有段内换行。</p>
<p>这是第二段内容。</p>

This conversion makes plain text content have basic formatting and readability when displayed on the front end.

truncatechars_htmlFilter: Truncate HTML intelligently

Next, let's take a look attruncatechars_htmlThis filter.Its core function is to truncate text based on the specified number of characters, but unlike ordinary text truncation, it can recognize and correctly handle HTML tags.This means it will not simply truncate at the character limit, causing HTML tags to be unclosed or the structure to be destroyed.

  • Calculate the number of visible characters, ignoring the characters occupied by the HTML tags themselves.
  • Intelligently close all open HTML tags at the truncation position, ensuring that the generated HTML is still valid and complete.
  • Automatically add an ellipsis at the end of truncated text (...),to indicate that the content is incomplete.

For example, if there is a segment of HTML content that is<strong>安企CMS</strong>是一个<em>强大的</em>系统。,we usetruncatechars_htmlto truncate it to 10 characters:<strong>安企CMS</strong>是一个...。It will close correctly.<strong>Labels, leaving no unclosed tags.

Combined usage:linebreaksWithtruncatechars_htmlThe perfect match

Now let's go back to our core issue: whenlinebreaksThe filter converts plain text to HTML,truncatechars_htmlCan it be truncated? The answer is affirmative, and this chaining call is highly recommended.

Working principle:

  1. You provide the original plain text content, for example fromarchive.Descriptionfields.
  2. linebreaksThe filter first processes this plain text, converting the newline characters to<p>and<br/>tags, generating anew, complete HTML fragment.
  3. This newly generated HTML snippet is passed in as input,truncatechars_htmlFilter.
  4. truncatechars_htmlThe filter receives this HTML and will, according to its design principles, intelligently identify and process these bylinebreaksGenerated HTML tags, while calculating the number of visible characters, ensure that all open tags are correctly closed at the truncation point (even if<p>Label, it also ensures that it is closed correctly). Finally, output a text with a limited length but a complete HTML structure, along with an ellipsis.

As an example:Assumearchive.DescriptionIt includes the following content:

安企CMS致力于提供高效解决方案。
它部署简单。
功能强大且易于扩展。

In the template, we can call it like this:

{{ archive.Description|linebreaks|truncatechars_html:30|safe }}

The output might be something like this:

<p>安企CMS致力于提供高效解决方案。<br/>它部署简单。功能...</p>

You can see that even if the text contains characters bylinebreaksgenerated<p>and<br/>tags,truncatechars_htmlAlso handles properly, ensuring that the output HTML is valid and meets the length requirements. Special attention should be paid to the fact that,linebreaksandtruncatechars_htmlAll generate or process HTML, so be sure to add it to the final output on the page|safeFilter to prevent HTML content from being doubly escaped, causing tags to be displayed directly instead of rendering their effects.

By this method, you can flexibly handle the original text input by users in the Anqi CMS, first performing basic formatting, followed by an elegant truncation, thus displaying standardized and beautiful content snippets in scenarios such as list pages and summaries.


Common Questions (FAQ)

1. Why not usetruncatecharsa filter to truncate text insteadtruncatechars_html? truncatecharsThe filter is designed for plain text truncation, it does not recognize HTML tags. If you passlinebreaksProcessed (HTML tags have been generated) text used directlytruncatecharsIt may be truncated within HTML tags, resulting in incomplete tags and disrupting the HTML structure of the page, causing display chaos.truncatechars_htmlThis exists precisely to avoid this situation, it can intelligently process HTML, ensuring the integrity of the truncated structure.

2. If I want to truncate by word count instead of character count and the content includes HTML, which filter should I use?AnQi CMS providestruncatewords_htmlFilter, its function is withtruncatechars_htmlSimilar, but it is truncated by word count.Similarly, it will also intelligently recognize and preserve the HTML structure.truncatewords_htmlwill be your ideal choice. The usage is the same astruncatechars_html类似,例如:{{ archive.Description|linebreaks|truncatewords_html:10|safe }}.

3. I used in the template:linebreaksandtruncatechars_html,but the front-end displayed it directly:<p>and<br/>标签,why is that?This is usually because you forgot to add at the end of the filter chain:|safeFilter.The CMS (and many template engines based on Django-like syntax) defaults to escaping all output as HTML to prevent XSS attacks.linebreaksandtruncatechars_htmlGenerated HTML code, if not|safeDeclared these codes as safe, the template engine will escape them as plain text, causing the tags to be displayed directly. Added|safeThis content is safe HTML, please render it directly.