When using AnQiCMS for website content display, the flexibility and security of the template are the focus of developers. AnQiCMS's template engine provides a rich set of filters to handle content, wherelinebreaksand|safeThese two filters often appear together and often raise questions among developers who are new to the field: whenlinebreaksAfter converting plain text to HTML content, do you still need to combine it with|safeWhat does the filter output? This article will delve into this issue.
linebreaksThe function and output format of the filter
Firstly, let's understand it.linebreaksThe core function of the filter. Its original design intention was to address the issue that newlines (\n) in plain text content cannot be directly interpreted as newlines by browsers.linebreaksThe filter will intelligently convert line breaks in plain text to HTML paragraph tags.<p>and newline tags<br/>In particular, it will convert consecutive single line breaks to<br/>And convert two or more consecutive newline characters (usually representing an empty line) into a pair of<p>tags to wrap a paragraph.
For example, if your text content is:
这是第一行。
这是第二行。
这是第三行。
AfterlinebreaksAfter the filter process, it may generate an HTML structure like this:
<p>这是第一行。<br/>这是第二行。</p>
<p>这是第三行。</p>
It is evident,linebreaksThe task is to "generate" HTML tags with formatted effects, making plain text content appear more beautiful and more readable in paragraph form on web pages.
AnQiCMS template engine's default security mechanism is with|safeFilter
AnQiCMS template engine takes a strict security strategy by default when handling variable output:All output variable contents will be escaped as HTML entitiesThis means that if a variable contains HTML tags (such as<p>/<a>/<script>[en] In the absence of additional processing, these tags will be converted to their HTML entity forms, for example<Will become<,>Will become>.This default escaping mechanism is to prevent cross-site scripting (XSS) attacks, ensuring that user input or content from untrusted sources, even if it contains malicious HTML or JavaScript code, will not be executed by the browser on the page but will be displayed as plain text.
while|safeThe role of the filter is precisely to remove this default escaping. When you use a variable|safeWhen you do this, you are explicitly telling the template engine: 'I know the content of this variable is safe HTML, please do not escape it any further and output it directly to the page in its original HTML structure.'
linebreaksWith|safeThe combination of: Why is it necessary?
Now let's go back to our core issue: Whenlinebreaksthe HTML content has already been generated, is it still necessary?|safe? The answer isYes, usually it is necessary..
Understanding this is crucial:linebreaksThe filter is responsible for converting plain text to HTML structure, but it does not mark whether the generated HTML content is 'safe'.The template engine will independently execute its default HTML entity escaping logic during the final rendering of the page.linebreaksGenerated some HTML, but this HTML has not been|safeIf marked, the template engine will still treat it as unescaped string and escape all HTML tags within it.
This means, even iflinebreaksyou painstakingly convert it into\n<p>and<br/>If you omit it when outputting, 【en】|safeThe browser will see it in a literal form, 【en】<p>and<br/>Instead of actual paragraphs and line breaks. The page will display the original, uninterpreted HTML tag text, losinglinebreaksthe formatting meaning it brings.
Therefore, when you uselinebreaksAn encoder to add HTML structure to text, since you have explicitly stated the source of the content and the intent of its HTML structure, and consider these structures to be harmless, then in order for the browser to correctly interpret these HTML tags and display the expected format, combined|safeThe filter output is necessary. For example:{{ archive.Description|linebreaks|safe }}.
Practical recommendations and safety considerations
In AnQiCMS template development, when you are dealing with text obtained from reliable sources (such as manually input by backend editors, or reviewed content), and you want to format it, linebreaks|safeIt is a very practical combination. It ensures that your text content can maintain the ease of editing of plain text while being presented elegantly in structured HTML on the front end.
However,|safeIt is not a panacea and its use should be cautious. Even if the content comes from user submissions or other unreliable external sources,linebreaksbe directly applied.|safeIt may also pose security risks because it "trusts" all incoming HTML. In this case, a better approach would be:
- Perform strict backend validation and filtering of user input content, allowing only safe HTML tags and attributes to pass.
- Consider using a more advanced rich text editor, which usually performs security filtering when saving the content or provides read-only mode when displaying on the front end, to reduce the risk of direct usage
|saferisk. - AnQiCMS documentation mentions that when the Markdown editor is enabled,
archiveDetailThe content will automatically convert Markdown to HTML, and it is recommended to combine it with|safe. This also proves from the side that even if the content is converted to HTML,|safeIt is indispensable when outputting.
Summary
linebreaksThe filter is responsible for converting newline characters in plain text to HTML tags to achieve better formatting; and|safeThe filter is responsible for indicating to the AnQiCMS template engine to output the contents containing HTML tags as 'safe' HTML directly, rather than escaping them as HTML entities.Both have their focuses, and collaboration is needed to present the content of the page in the structure and style expected by the developer while ensuring safety.linebreaksThe content after transformation indeed needs to be combined|safeFilter output.
Common Questions and Answers (FAQ)
Why does the AnQiCMS template engine default to escaping HTML?The AnQiCMS template engine defaults to HTML escaping to enhance website security, mainly to prevent cross-site scripting attacks (XSS).Cross-site scripting (XSS) attacks involve injecting malicious scripts into web pages, which may steal user data, tamper with page content, or perform other malicious operations.
</>Special characters such as these will be converted to</>HTML entities, thus preventing malicious scripts from being parsed and executed by the browser, ensuring the security of the website and users.Except
linebreaksWhat other filters might generate HTML content and need|safeto be output with?ExceptlinebreaksAnQiCMS template engine also has some filters that generate HTML structures, and they usually also need|safeto ensure correct rendering:urlizeThe text will automatically convert URLs and email addresses to clickable links<a>Label.truncatechars_htmlandtruncatewords_htmlIn truncating HTML content, efforts are made to maintain the integrity of the HTML structure and generate an ellipsis, with the output result containing HTML tags.renderFor example:archiveDetail[提及,when the content is Markdown and needs to be rendered as HTML,]renderThe filter will perform a transformation, and its output is also HTML. In short, any filter that outputs HTML tags rather than plain text, under the premise of content security being可控, may need to|safe.
If I use
|safeWhat would be the consequences of outputting user comments containing malicious scripts? How can the risks be avoided?If you use|safeoutputting malicious scripts (such as)<script>alert('XSS')</script>The user comment of ) will be executed by the browser when other users visit the page.This may lead to serious consequences such as session hijacking, data leakage, and website tampering.- strict input validation and filteringEnsure all input is validated on the server before being submitted to the database, removing or escaping all potential malicious HTML and JavaScript code. A whitelist mechanism can be used to allow only a few known safe tags (such as
<b>/<i>Passed - Contextual escapingAvoid using it in unnecessary scenarios
|safeUse it only when you are sure the content is safe HTML. - Content reviewFor User Generated Content (UGC), implement manual or machine review to ensure content compliance and safety.
- Use a secure rich text editor.If users are allowed to use a rich text editor, choose those that come with built-in security filters, which clean up unsafe HTML when saving and loading.
- strict input validation and filteringEnsure all input is validated on the server before being submitted to the database, removing or escaping all potential malicious HTML and JavaScript code. A whitelist mechanism can be used to allow only a few known safe tags (such as