How to convert newline characters in multi-line text to HTML's `
tag for display?

Calendar 👁️ 74

In AnQiCMS content management, we often enter multi-line text with line breaks, such as article content, product descriptions, or contact addresses.However, when this content is displayed on the front end of the website, we may find that the original line breaks have disappeared and all the text is squeezed into a line.This not only affects the reading experience of the content, but may also be inconsistent with our original design intention.

Why is this happening? In simple terms, the HTML specification dictates that browsers automatically ignore single line breaks in text when rendering web content (\n)and consecutive whitespace characters are treated as a single space. Only<p>tags (paragraphs) or<br>Labels (newline) are required to produce a visual line break. Therefore, even if we press the Enter key in the background content editor, these line breaks in plain text are just a normal space in the browser.

AnQiCMS's template system is based on the powerful Django template engine syntax and provides simple yet powerful template filters (filters) to elegantly solve this problem, ensuring that your multi-line text content is displayed in the expected format.

Template filter: A tool to solve the problem of line break display

AnQiCMS provides two core filters to handle line breaks in plain text:linebreaksandlinebreaksbr. They work by converting line breaks in text to the corresponding HTML tags.

  1. linebreaksFilterThis filter will convert each independent or consecutive newline character in the text to an HTML paragraph tag<p>and</p>If one is in a<p>The tag contains line breaks, it will further convert these internal line breaks into<br/>Label. This is very suitable for processing the main body of an article, as it can automatically divide your content into standard paragraphs and maintain line breaks within paragraphs.

    Usage example:Assumearchive.ContentIs the main content of your article, which contains multiline text.

    <div class="article-content">
        {{ archive.Content|linebreaks|safe }}
    </div>
    

    afterlinebreaksAfter processing, the original:

    这是第一段文字。
    这是第一段的第二行。
    
    这是第二段文字。
    

    May be converted to:

    <p>这是第一段文字。<br/>这是第一段的第二行。</p>
    <p>这是第二段文字。</p>
    
  2. linebreaksbrFilterThis filter is more direct and simple. It will only convert each newline character in the text to a\nand it will not add any additional<br/>tags.<p>Label wrapping. This is applicable to content that does not require paragraph semantics but needs to maintain line breaks, such as brief descriptions, address information lists, etc.

    Usage example:Assumecategory.DescriptionIs a brief description of the category, or a contact address, which needs to be displayed strictly line by line.

    <address>
        {{ category.Description|linebreaksbr|safe }}
    </address>
    

    afterlinebreaksbrAfter processing, the original:

    联系地址:某某市某某区
    电话:123-4567-890
    

    Will be converted to:

    联系地址:某某市某某区<br/>电话:123-4567-890
    

Where should these filters be applied?

These filters can be directly applied to variables in the AnQiCMS templates used to display multi-line text. Common application scenarios include:

  • Document Details Page:Displayarchive.Content(Content of the article),archive.Description(Article summary) et al.
  • Category details page:Displaycategory.Content(Category content),category.Description(Category description) et al.
  • Single page detail page:Displaypage.Content(Single page content),page.Description(Single page description) and so on.
  • Custom field:Any custom field defined in the content model as 'Multiline text', which also contains line breaks, can use these filters.

Choose the appropriate filter

  • Uselinebreaks:If your multiline text is a long paragraph, you want it to be displayed in a structured manner like a normal article, with spacing between each natural paragraph, and the internal line breaks become single line breaks, thenlinebreaksIt is an excellent choice. It will give you clearer paragraph structure.
  • Uselinebreaksbr:If your multiline text is a short address, phone number list, or you just want to simply convert each newline character into an HTML line break tag without additional paragraph tags wrapping, thenlinebreaksbrIt is more suitable, as it provides the most direct line break effect.

Special reminder:|safeThe importance of the filter

Whether it is usinglinebreaksOrlinebreaksbrFilter, you need to add one after it.|safea filter such as{{ my_variable|linebreaks|safe }}This is becauselinebreaksandlinebreaksbrIt will generate HTML tags(<p>and<br/>),而 AnQiCMS 的模板引擎默认为了安全考虑,会自动对所有输出的 HTML 标签进行转义(例如把<to&lt;)。如果不加|safeThese tags will be displayed as plain text on the page, rather than being parsed by the browser as line breaks.|safeTell the template engine that you trust this content is safe HTML and allow it to be rendered normally by the browser.

By simply adding after the template variable|linebreaksor|linebreaksbrThe filter allows you to easily display multi-line text content in AnQiCMS on the web in a more beautiful and expected manner.This not only improves the user reading experience, but also makes your website content management more flexible and efficient.

Frequently Asked Questions (FAQ)

  1. Q: Why did I use|linebreaksor|linebreaksbrAfter, the content still does not wrap even<br>The tags are displayed directly?A: This is likely because you forgot to add at the end of the filter chain|safeFilter. AnQiCMS's template engine, to prevent XSS attacks, defaults to escaping all possible HTML output.|safeThe filter informs the template engine that this content is safe HTML that can be normally parsed and rendered by the browser, rather than displayed as plain text. For example, the correct syntax should be{{ archive.Content|linebreaks|safe }}.

  2. Q: Should I chooselinebreaksOrlinebreaksbrFilter? What are the differencesA: It depends on the display effect and semantic content you hope for.

    • linebreaksFilters will convert consecutive newline characters in text to<p>Label, and<p>Converts a single newline character within a<br/>. It is suitable for long text that needs to be structured into paragraphs (such as article content), the browser will<p>Label adds default paragraph spacing.
    • linebreaksbrThe filter is more direct, it will only convert each newline in the text to a single one.<br/>tags.<p>Label. This applies to addresses, list items, or brief descriptions that do not require paragraph semantics,

Related articles

How to remove specific HTML tags from an HTML string in the AnQiCMS template (such as `<i>`, `<span>`)?

In AnQiCMS template development, we often encounter content coming from rich text editors, or imported from external sources, which may contain some HTML tags that we do not want to display at specific locations.For example, in the summary section of the article list, we may only want to display plain text, or we may need to remove specific tags such as `<i>`, `<span>`, etc. to maintain the consistency of the page style.

2025-11-07

How to truncate a long string (such as an article summary) to a specified length and display an ellipsis in the AnQiCMS template?

In website content operation, the display length of article abstracts or introductions often needs careful control.Long content can affect the layout and user experience of a page, while a concise summary with an ellipsis can effectively guide users to click and read more details.AnQiCMS provides flexible template tags and filters, allowing us to easily implement this feature.

2025-11-07

How to judge whether a variable is empty in AnQiCMS template and set a default display value?

During the development of website templates, it is often encountered that the variable value may be empty.If not properly handled, the front-end page may appear with unattractive blank areas, even displaying some default placeholders (such as `nil` or `null`), which undoubtedly affects user experience and the professionalism of the website.AnQiCMS (AnQiCMS) provides a powerful and flexible template engine that can help us elegantly determine whether variables are empty and set appropriate default display values.

2025-11-07

How to dynamically display the Title, Keywords, and Description information of the website homepage in AnQiCMS template?

In website operation, the Title (title), Keywords (keywords), and Description (description) of the homepage are the first impression given to users on the search engine results page (SERP) and are also the key for search engines to understand the core content of the website.They not only affect the website's search engine optimization (SEO) effect, but also directly relate to whether users will click to enter your website.AnQiCMS as a feature-rich enterprise-level content management system provides a straightforward and powerful way to manage these important SEO elements. Next

2025-11-07

How to calculate the number of elements in a string (such as an article title) or an array (such as a tag list) in AnQiCMS templates?

In AnQi CMS template design, we often need to make accurate statistics of the content on the page, whether it is to dynamically display the number of data or to make conditional judgments based on the number, mastering how to calculate the number of elements in a string or array is particularly important.AnQiCMS's powerful template engine provides a concise and efficient method to handle these requirements.

2025-11-07

How to automatically convert a URL string into a clickable hyperlink and set `nofollow` in the template of AnQiCMS?

In the daily operation of AnQi CMS, we often need to display external links in the website content.These links, if they are just simple text, not only affect the user experience, but also cannot effectively convey information.At the same time, in order to follow the **practice** of search engine optimization (SEO), especially for links pointing to external sites, we usually want to add the `rel="nofollow"` attribute to avoid unnecessary "weight loss" or passing unnecessary trust.AnQi CMS provides a simple and efficient method to solve this problem.### Core Function Revelation

2025-11-07

How to format a floating-point number to a specified number of decimal places in AnQiCMS template?

In the presentation of website content, we often need to display various numbers, such as product prices, discount percentages, or statistical data.These numbers are often floating-point numbers, and in order to ensure the beauty of the page layout and the clarity of the information, we usually need to format them, such as uniformly retaining two decimal places.In the AnQiCMS template, thanks to its flexible template engine, we can conveniently use the built-in `floatformat` filter to meet this requirement.

2025-11-07

How to implement the conversion of the first letter to uppercase or all uppercase of the string in AnQiCMS template?

In website content presentation, the case format of strings often needs to be flexibly adjusted according to different scenarios, such as the first letter of the article title in uppercase, the username in all lowercase, or the brand name in all uppercase.AnQiCMS as a feature-rich enterprise-level content management system, its template engine provides convenient and powerful filters (Filters), which help us easily implement the case conversion of these strings, making content display more standardized and professional.

2025-11-07