How to convert multi-line text (including newline characters) in a template to an HTML paragraph or `
tag display?

Calendar 👁️ 92

In website content operations, we often encounter such situations: the back-end text input box allows users to input multiline text, such as article summaries, product descriptions, contact addresses, etc.When these multi-line texts containing line breaks are displayed in a website front-end template, if output directly, we will find that the original line breaks do not take effect, and all the text is squeezed into a single line.This is because the browser defaults to merging consecutive whitespace characters (including newline characters) into a single space.So, how can we elegantly convert these multiline text to HTML paragraphs in AnQiCMS<p>) or a newline character (<br/>) in the format so that it is displayed correctly on the page?

AnQiCMS uses a template engine syntax similar to Django, providing powerful filter functions to handle such issues. Among them,linebreaksandlinebreaksbrThese filters are specifically designed for this.

Understand the root cause: the browser's handling of newline characters.

Firstly, we need to understand why the direct output of multiline text does not work. When you enter:

第一行文字
第二行文字

第三行文字

This text is usually stored in the database as\n(Newline) Store. If you enter it directly in the template{{ item.Description }}Output, the browser will treat it as plain text. In the HTML standard, the browser will ignore most whitespace between tags, including newline characters.Therefore, the above text will be displayed as 'First line text Second line text Third line text', with all line breaks replaced by a space.In order to make line breaks take effect, we need to\nConvert to HTML in<br/>tags, or convert paragraphs into<p>.

AnQiCMS's solution:linebreakswithlinebreaksbrFilter

AnQiCMS provides two main filters to solve this problem, each with its focus:

1.linebreaksFilter: intelligently converts to paragraphs and line breaks

linebreaksThe filter works more intelligently. It recognizes consecutive newline characters:

  • Two or more consecutive newline characters(A block of text separated by blank lines) will be converted to an HTML paragraph tag<p>...</p>.
  • A single newline(A natural line break within the text) will be converted to an HTML line break tag<br/>.

This filter is very suitable for processing multi-line text that has paragraph concepts, such as detailed descriptions or summaries of articles, it can automatically generate a reasonable paragraph structure for the text content.

Usage example:

Assumearchive.DescriptionThe value is:

这是文章的第一段。

这是文章的第二段。
它包含一个内部换行。

Use it like this in the template:

<div class="description-area">
    {{ archive.Description|linebreaks }}
</div>

Possible output HTML (if you forget):|safe):

<div class="description-area">
    <p>这是文章的第一段。</p>
    <p>这是文章的第二段。<br />它包含一个内部换行。</p>
</div>

Here is a key point: If you directly copy the code and run, you might find out that:<p>and<br/>The tag is displayed as plain text, not as actual line breaks. This leads to another important filter:safe.

2.linebreaksbrFilter: Simply converts to line breaks directly

linebreaksbrThe filter is simpler and more direct. It will convert each newlinein the text to HTML tags. It does not attempt to generate\n)HTML tags. It does not attempt to generate<br/>any content.<p>.

This filter is suitable for those who do not need complex paragraph structures and only need to display each line independently, such as contact addresses, project lists, poems, and so on.

Usage example:

Assumecontact.AddressThe value is:

广东省深圳市南山区
科技园深南大道10000号
某某大厦10层

Use it like this in the template:

<address>
    {{ contact.Address|linebreaksbr }}
</address>

Possible output HTML (if you forget):|safe):

<address>
    广东省深圳市南山区<br />科技园深南大道10000号<br />某某大厦10层
</address>

Similarly, there is also a problem with the escaping of tags.

Key security measures:safeFilter

whether it islinebreaksOrlinebreaksbrThey will all convert text content to HTML tags. The AnQiCMS template engine, for security reasons (to prevent cross-site scripting attacks XSS), defaults to escaping all output HTML content, that is,<to&lt;,>to&gt;EvenlinebreaksGenerated<p>or<br/>Tags, they will be escaped as strings and displayed on the page, rather than being parsed as HTML elements by the browser.

We must use to solve this problemsafefilter.safeThe filter explicitly tells the template engine that the content of this variable is 'safe' HTML, which does not need to be escaped and can be output directly.

The correct usage:

tolinebreaksorlinebreaksbrthe filter meetssafeUse filters in combination and make suresafeThe filter is the last in the chain of calls.

{# 使用 linebreaks 转换为段落和换行 #}
<div class="description-area">
    {{ archive.Description|linebreaks|safe }}
</div>

{# 使用 linebreaksbr 转换为纯换行 #}
<address>
    {{ contact.Address|linebreaksbr|safe }}
</address>

This way, you can see the text content displayed on the page in paragraphs or line breaks as expected.

Application scenarios and precautions

  • Description or summary (archive.Description): Often contains multiple paragraphs, using{{ archive.Description|linebreaks|safe }}Can automatically generate paragraph structure.
  • Product features or parameters (archive.FeaturesOr custom multi-line text field): If there are line breaks between features, but no strict paragraph structure.

Related articles

How to display a preset default value (such as "No data") for empty variables in the template?

In website operation, the completeness of content display and user experience is crucial.When we call data in AnQiCMS (AnQiCMS) template, we sometimes encounter the situation where some variables are empty.If these empty variables are not processed, the front-end page may appear blank areas, 'null' text, and even cause layout disorder, thus affecting the professionalism of the website and the user's browsing experience.

2025-11-08

How to use the filter (filter) to truncate, convert case, or escape HTML in displayed text?

When building a website, we often need to process various text content displayed on the page, such as limiting the length of article abstracts, unifying the case format of user input, or ensuring that user submitted content can be safely displayed on the page without destroying the page structure.AnQiCMS (AnQiCMS) provides us with powerful template filter functions, which can efficiently and conveniently complete these tasks.The filter is a very practical tool in the Anqi CMS template, which helps us quickly process and format the data displayed on the page.

2025-11-08

How to perform simple arithmetic operations such as addition, subtraction, multiplication, and division in AnQiCMS templates?

When creating templates in AnQiCMS, we often need to perform some simple numerical calculations, such as displaying the total price of goods, calculating the percentage of article reading volume, or handling the serial numbers in the list.AnQiCMS is a powerful template engine that supports direct arithmetic operations such as addition, subtraction, multiplication, and division in templates, making our content display more flexible and dynamic.

2025-11-08

How to display a list of related documents on the document detail page, such as categorized recommendations or keyword-based recommendations?

In website content operation, providing more relevant and potentially interesting content to visitors is a key strategy to enhance user experience, extend website stay time, and promote in-depth content browsing.This not only effectively guides users to explore more information, but is also an important component of 'inter-page relevance' in Search Engine Optimization (SEO).In such a powerful content management system as AnQiCMS, it is easy and efficient to implement the display of related document lists on the document detail page.

2025-11-08

How to automatically identify and convert URL strings in text to clickable HTML links?

Bring URLs to life in text: The Practical Guide to Automatic Link Conversion in Anqi CMS In daily website content operations, we often encounter situations where a large number of web links are included in the text content copied and pasted from various sources.These links, if only existing in plain text form, not only cannot be clicked to jump, affecting user experience, but also cause potential traffic and information transmission opportunities to be lost in vain.

2025-11-08

How to safely display content containing HTML tags or JavaScript code in a template and prevent XSS attacks?

Building website templates in AnQiCMS (AnQiCMS), ensuring the safe display of content is a core issue, especially when the content may contain HTML tags or JavaScript code, how to effectively prevent cross-site scripting (XSS) attacks is particularly important.AnQi CMS is a Go language content management system that focuses on security and considered these security challenges from the outset, providing mechanisms to help users manage and control the rendering of content.

2025-11-08

How to display a comment list on the website front end and support pagination, replies, and review status distinction?

The website comment section is an important battlefield for user communication and content feedback. A well-designed and functional comment system can greatly enhance the activity and user stickiness of the website.AnQiCMS provides us with a flexible and powerful comment management feature, whether you want to display comments, implement reply interaction, or differentiate according to the review status, you can easily achieve this through simple template tags.This article will introduce in detail how to efficiently display comment lists on the website front-end, and implement features such as pagination, reply, and review status distinction.### One, Basic Display of Comment List

2025-11-08

How to build a comment form in a template and dynamically display custom fields from the backend?

In website operation, the feedback form is an important bridge for interaction with users, collecting feedback, and establishing contact.AnQiCMS (AnQiCMS) provides a powerful and flexible message feature, which not only allows users to quickly build basic forms but also supports custom fields through the backend to make forms dynamically adapt to various business needs.This article will delve into how to build such a comment form in Anqi CMS templates and dynamically display these custom fields from the backend.

2025-11-08