In the presentation of website content, the formatting of text is often the key to determining the user's reading experience. We often encounter such needs: the text content obtained from the background database usually only contains simple line breaks (\n),If displayed directly on a webpage, the browser will not intelligently convert these newline characters into the HTML paragraphs we expect (<p>) or line breaks (<br>The tag causes the content to be cramped together, losing its original structure and readability.

AnQiCMS (AnQiCMS) has fully considered this point in template design, providing a series of convenient built-in filters that can help us easily convert newline characters in plain text to standard HTML tags, ensuring that the content is presented naturally and beautifully on the front-end page.These filters are like intelligent formatting tools, which can easily solve complex text layout problems.

Core mechanism: Understanding AnQiCMS text processing filter

The Anqi CMS template engine adopts a syntax similar to Django, one of its core advantages is the flexible 'filter' function.The filter allows us to modify and format the output content of a variable.For line break conversion, AnQiCMS mainly provideslinebreaksandlinebreaksbrThese two filters, each suitable for different text formatting needs.

1.linebreaksFilter: Smart segmentation and inline line breaks

When processing articles, long descriptions, or comments, we expect them to be automatically segmented on the web like traditional text, with new paragraphs formed where there are blank lines, and the line breaks within paragraphs to be preserved, whenlinebreaksThe filter is an ideal choice.

linebreaksThe principle of operation is as follows:

  • Converts consecutive two newline characters(\n\n)to HTML paragraph tags<p>...</p>.This means that in the original text, if you create an empty line by pressing Enter twice,linebreaksit will be recognized as a new paragraph.
  • a single newline character (\n) to an HTML newline tag<br>.If you press the enter key once only within a paragraph, and you want the content to continue on the next line without starting a new paragraph,linebreaksit will add one for it<br>.

For example, assume that the text content transmitted from the backgrounditem.descriptionAs follows:

这是一段产品描述。
产品特点一。
产品特点二。

这是另外一段说明。
请注意相关事项。

In the template, you can use it like thislinebreaksFilter to output:

{{ item.description|linebreaks|safe }}

here,|safeThe filter is crucial. Because it tells the template engine, afterlinebreaksThe processed content is safe HTML and does not need to be default HTML entity encoding (such as changing <p>Escape to&lt;p&gt;Thus ensuring that the browser can correctly parse and render these HTML tags.

After such processing, the final HTML structure rendered on the web page will be: "`html"

This is a product description.
Product feature one.<br>