How to automatically convert line breaks in user input plain text content to HTML's `
` tag?

Calendar 👁️ 80

In daily website content operations, we often need to enter some multi-line text content in the Anqi CMS backend, such as the introduction of articles, the characteristics of products, or detailed descriptions in custom fields.This content is usually entered in plain text format, however, when we expect them to be displayed on the front-end web page with the original paragraph and line break effects, we find that they are often cramped into a line and lose their original formatting.

This is not a problem with the AnQi CMS system itself, but a feature of the HTML web page rendering mechanism.In HTML, the browser defaults to treating all carriage returns (i.e., newline characters) as spaces and does not automatically wrap.Only when the content includes<p>(paragraph) or<br/>(Forced line break) When such HTML tags are used, the browser will display line breaks or paragraphs according to the tag instructions.

The Anqi CMS solution: powerful text filter

To ensure that the raw line break effect of the pure text content entered by the user is perfectly presented on the front-end web page, Anqi CMS provides a flexible and powerful template filter mechanism. Among them,linebreaksandlinebreaksbrThese filters are designed to solve the problem of line breaks in plain text.

These filters can intelligently parse the newline characters in plain text and automatically convert them into HTML newline tags recognized by the browser, thus perfectly preserving the original formatting you entered in the background.

Get to know in-depthlinebreaksandlinebreaksbr

  1. linebreaksbrFilter: A simple and direct line breakThis filter is the most direct solution, it will replace every line break in plain text content (\n) with HTML's<br/>Label. This means that no matter how many times you press Enter in the background, the front-end page will display a forced line break at the corresponding position.

    Usage example:Assuming the content you enter in the background is:

    第一行文字
    第二行文字
    第三行文字
    

    Used in the front-end templatelinebreaksbrFilter, code as follows:

    {{ 你的纯文本变量|linebreaksbr|safe }}
    

    It will be rendered as:

    第一行文字<br/>
    第二行文字<br/>
    第三行文字
    
  2. linebreaksFilter: More intelligent paragraph processingCompared tolinebreaksbrSimple and rough,linebreaksThe filter becomes more intelligent and semantically appropriate. It does two things:

    • Convert a single newline (\n)to<br/>.
    • It replaces two or more consecutive newline characters (i.e., paragraphs separated by blank lines) with<p>and</p>wrap in tags to form a standard HTML paragraph.

    Usage example:Assuming the content you enter in the background is:

    这是第一段。
    这里是第一段的第二行。
    
    这是第二段。
    

    Used in the front-end templatelinebreaksFilter, code as follows:

    {{ 你的纯文本变量|linebreaks|safe }}
    

    It will be rendered as:

    <p>这是第一段。<br/>这里是第一段的第二行。</p>
    <p>这是第二段。</p>
    

    You can choose a filter that suits your specific content formatting needs. If the content is mostly short sentences or lists,linebreaksbrMaybe more appropriate; if the content is structured paragraph articles,linebreaksthey can provide better HTML semantics.

Why is it needed|safe?

While usinglinebreaksorlinebreaksbrwhen using filters, you will notice that they are all followed by a|safeFilter. This is a very critical step!

The AnQi CMS template system, for security reasons, defaults to escaping all output variables with HTML entities to prevent cross-site scripting (XSS) attacks. This means that if the filter will\nto<br/>There is not|safeThe browser will not display a line break, but will display it directly<br/>this text string.

|safeThe filter tells the template engine: "I know this variable outputs HTML content, please do not escape it, parse and display it directly as HTML." Therefore, when you uselinebreaksorlinebreaksbrThis filter that generates HTML tags must be added|safe.

Where can these filters be used?

These powerful text filters can be applied anywhere that stores plain text and needs to retain line breaks:

  • Article details(archiveDetail)的ContentorDescriptionField:
    
    {% archiveDetail articleContent with name="Content" %}
    <div class="article-body">
        {{ articleContent|linebreaks|safe }}
    </div>
    
  • Category details(categoryDetail)的ContentorDescriptionField:
    
    {% categoryDetail categoryDesc with name="Description" %}
    <p class="category-description">
        {{ categoryDesc|linebreaksbr|safe }}
    </p>
    
  • Single page (pageDetail)的ContentField:
    
    {% pageDetail pageText with name="Content" %}
    <div class="page-content">
        {{ pageText|linebreaks|safe }}
    </div>
    
  • Content Model Custom Field:If you define a multi-line text type custom field in the content model, for exampleproduct_featuresIt can also be handled in this way:
    
    {% archiveDetail features with name="product_features" %}
    <div class="product-features">
        {{ features|linebreaksbr|safe }}
    </div>
    

Practice: Make the article content automatically wrap

Suppose you are editing an Anqi CMS article detail page template (such asarticle/detail.html), and you want the main content of the article to be displayed according to the line break effect entered in the background.

  1. Find the output position of the article content, usually it would be something like{{ archive.Content }}Or througharchiveDetailThe content obtained by the tag.
  2. applylinebreaksorlinebreaksbrFilter, and add|safe.

Example code snippet:

{# 获取当前文章的完整内容 #}
{% archiveDetail articleContent with name="Content" %}

<article class="main-article">
    <h1 class="article-title">{% archiveDetail with name="Title" %}</h1>
    <div class="article-meta">
        发布时间:<span>{% archiveDetail with name="CreatedTime" format="2006-01-02" %}</span>
        分类:<a href="{% categoryDetail with name='Link' %}">{% categoryDetail with name='Title' %}</a>
    </div>
    <div class="article-body">
        {# 使用 linebreaks 过滤器,将纯文本换行符转换为 HTML 段落和换行标签 #}
        {{ articleContent|linebreaks|safe }}
    </div>
</article>

By following these steps, the plain text content you enter in the Anqi CMS background will be able to automatically and correctly achieve line breaks and paragraph effects on the front-end web page, greatly enhancing the flexibility of content display and user experience.


Frequently Asked Questions (FAQ)

  1. Q: When should it be usedlinebreaksAnd when should it be usedlinebreaksbrWhat are the differences? A:It mainly depends on your needs for formatting.linebreaksbrMore direct, it will simply convert each newline (carriage return) to a<br/>Tags are suitable for handling lists, addresses, poems, or brief descriptions, and retain the original line-by-line display. Whilelinebreaksit is more intelligent, it will convert a single newline character to<br/>But will recognize text blocks separated by empty lines as different paragraphs, and enclose them with<p>tags, which is more suitable for processing structured article text and providing better HTML semantics.

  2. Q: I have already usedlinebreaksbrthe filter, but the text displayed on the webpage is still<br/>this text does not actually wrap. What's the matter? A:This situation may be caused by your forgetting to add after the filter|safeLabel. The Anqi CMS template system defaults to escaping all output variables to prevent security issues. So, whenlinebreaksbra filter to convert line breaks into<br/>If not after,|safeLabel to clearly tell the template system

Related articles

How to prevent XSS attacks and correctly escape HTML special characters when outputting article content in a template?

Managing and displaying content in AnQiCMS is the core task of website operation, but it is also crucial to ensure that these contents are presented safely and securely to users.Among them, cross-site scripting (XSS) attacks are a risk that should not be ignored, which may allow malicious code to be executed in the user's browser accessing your website, thereby triggering a series of security issues, such as stealing user data, tampering with page content, and even hijacking user sessions.

2025-11-09

Extract the article summary by word count instead of character count, which filter should be used in the template?

In website content operation, the way articles are presented often directly affects readers' click intentions and reading experience.A clear and concise summary that helps readers quickly understand the main theme of the article.Especially in scenarios such as list pages and recommendation areas, we usually hope that the abstract can be intelligently extracted, controlling the length while maintaining readability.When it comes to generating abstracts based on the content of an article, the length of the excerpt is a core consideration.There are two common ways to truncate: by character count and by word count.Cutting by character count is accurate, but it often encounters the situation where words are abruptly cut off

2025-11-09

How to safely extract the content of an article containing HTML tags without destroying its structure?

In website content management and display, we often need to display the partial content of articles in article lists, homepage summaries, or related recommendation areas to attract readers to click.However, directly truncating the content of an article containing HTML tags can easily disrupt the original HTML structure, causing the page to display incorrectly and even affecting the overall layout and user experience.AnQiCMS (AnQiCMS) fully understands this pain point, its powerful template engine and built-in filters provide an elegant and secure solution, allowing you to worry-free about display issues caused by content truncation. Next

2025-11-09

How to extract the article title and display an ellipsis in Anqi CMS template?

In AnQi CMS template development, it is often encountered that article titles need to be displayed on the list page, but in order to ensure the beauty of the layout and unified layout, long titles need to be truncated and abbreviated with an ellipsis.This has improved the user experience and also made the page look cleaner and more professional.AnQi CMS with its flexible Django template engine syntax makes it very direct and efficient to implement this requirement.

2025-11-09

How to count the number of times a specific keyword appears in the title or description of an article?

As users of Anqi CMS, we often need to manage and analyze website content in a refined manner, one common requirement being to count the frequency of specific keywords in article titles or descriptions.This not only helps us understand the effectiveness of content marketing, optimize SEO strategies, but also better grasp user concerns.AnQi CMS with its flexible template engine and rich built-in filters makes this operation feasible at the front-end template level.

2025-11-09

How to configure multiple sites in AnQiCMS to achieve independent display of content under different domain names?

AnQiCMS provides powerful multi-site management features, allowing you to easily operate multiple independent websites on the same system, each with its own domain and content.This is undoubtedly a very convenient and efficient solution for operators who have multiple brands, sub-sites, or need to provide differentiated content for different audience groups.Through a unified backend management entry, you do not have to deploy a separate system for each site, which greatly simplifies the operation and maintenance work, while also ensuring the complete independence of the front-end content display.Next, we will discuss in detail how to use AnQiCMS

2025-11-09

How to customize a content model for specific business needs and elegantly display its content on the front end?

In website content operation, we often encounter situations where we need to display diverse information.Traditional CMS may only provide fixed types such as 'articles' or 'products'. When business needs become more complex, such as displaying real estate information, job openings, event schedules, etc., these fixed types often seem inadequate.At this time, the flexible content model function of AnQiCMS is particularly important, it allows us to tailor the data structure to meet specific business needs and present the content in the way we want on the front end.Why do we need a custom content model?Imagine

2025-11-09

How does AnQiCMS support the switching and correct display of multilingual content?

AnQiCMS demonstrates excellent support capabilities in global content promotion. It provides a flexible mechanism to help us switch between multilingual content and display it correctly, thereby effectively reaching user groups from different language backgrounds. ### Core Mechanism: Making Content Speak Multiple Languages AnQiCMS's multilingual support is not just about translating the website interface, but also deeply involves the organization and presentation strategies of content.In its design philosophy, the implementation of multilingualism is mainly reflected in two levels: one is the localization processing of static text at the system level and template level.

2025-11-09