How to safely remove all or part of a specified tag from HTML content in AnQiCMS templates?

Calendar 👁️ 64

When building a website with AnQiCMS, we often need to finely control the content displayed on the page.In particular, when dealing with user submitted content, importing articles from different sources, or simply to maintain consistency in the page style, you may encounter the hassle of HTML tags.These tags may contain unnecessary formatting, style, and even potential security risks. 幸运的是,AnQiCMS template system provides a flexible mechanism to help us safely and efficiently remove all or part of the specified tags from the HTML content.

Why do we need to remove HTML tags?

There are many different needs to remove HTML tags in content management:

  • Unified content display:For example, we may want to display plain text summaries in the article list instead of complex styled HTML paragraphs, or we may want to standardize the title style, removing any possible HTML content included in the article.<h1>to<h6>Wait for the title tag.
  • Improve user experience:Removing unnecessary tags can make the page load faster and reduce layout issues caused by external style conflicts.
  • Enhance content security:Although AnQiCMS defaults to HTML-escaping content to prevent common cross-site scripting (XSS) attacks, manually removing some potentially dangerous tags can still provide additional security in certain scenarios where raw content needs to be output directly.
  • Adapt to different scenarios:The same content may need to be presented in different forms in different template parts, for example, on the article detail page, you need complete rich text content, while in the sidebar recommendation module, you only need plain text title and summary.

The AnQiCMS template system, with syntax similar to the Django template engine, provides several powerful filters (Filters) to achieve this goal, the most commonly used beingremovetagsandstriptags.

Precision strike: Remove specified tag (removetags)

When we need to selectively remove specific tags from HTML content while retaining other tags and text,removetagsThe filter can be used. This filter allows us to list the names of the tags that need to be removed, separated by commas.

For example, let's assume we have a piece of content<strong><i>你好!</i>这是一个<p>段落</p></strong>We may wish to remove the italic from it<i>tags, but retain the bold<strong>and paragraphs<p>.

We can use it like thisremovetagsFilter:

{{ "<strong><i>你好!</i>这是一个<p>段落</p></strong>"|removetags:"i"|safe }}

Here|removetags:"i"instruct the template engine to remove all<i>tags and their content. The final output will be:

<strong>你好!这是一个<p>段落</p></strong>

If we need to remove multiple tags, just list them separated by commas:

{{ "<strong><i>你好!</i>这是一个<p>段落</p></strong>"|removetags:"i,p"|safe }}

This will remove:<i>and<p>Tags, output:

<strong>你好!这是一个段落</strong>

It should be noted that,removetagsRemove the entire tag and its content. If you only want to remove the tag while keeping the text inside, a more complex processing is required, but this goes beyondremovetagsthe direct function of the filter.

Completely clean: remove all labels (striptags)

Sometimes, our goal is to obtain completely pure text content, without any HTML tags. At this point,striptagsThe filter is the ideal choice. It will remove all HTML tags, including their attributes, leaving only plain text.

Continue using the above example, if we want to get<strong><i>你好!</i>这是一个<p>段落</p></strong>the plain text content:

{{ "<strong><i>你好!</i>这是一个<p>段落</p></strong>"|striptags|safe }}

by applyingstriptagsa filter, all tags will be removed, the output will be:

你好!这是一个段落

striptagsIt is a very convenient tool, especially suitable for displaying article summaries, descriptions, or any place that only needs plain text.

about|safeImportant notes on the filter

While usingremovetagsorstriptagsWhen filtering, you may notice that a sample code often follows|safeFilter. This is because the AnQiCMS template system defaults to escaping all output content to prevent XSS attacks.This means, if there is not|safe, even if you remove some tags, the remaining HTML structure (such as<strong>) will be escaped into&lt;strong&gt;Display on the page, rather than being parsed by the browser as bold text.

For example:

{# 移除 i 标签,但不使用 |safe #}
{{ "<strong><i>你好!</i>这是一个<p>段落</p></strong>"|removetags:"i" }}

The output will be:

&lt;strong&gt;你好!这是一个&lt;p&gt;段落&lt;/p&gt;&lt;/strong&gt;

To let passremovetagsorstriptagsThe processed HTML content (ifremovetagsleft HTML)can be parsed normally by the browser, we need to explicitly tell the template engine that this content is 'safe' and does not need to be escaped, which is where we use|safefilter.

Therefore, when you want the remaining HTML structure to render normally after removing a specific tag, you must add it at the end of the filter chain|safe.

Application scenarios in practice

These filters are widely used in the AnQiCMS template, especially when displaying document content (archive.Content)Document Description(archive.Description) or custom fields.

Assuming we need to display article summaries on a list page, we do not want any HTML tags to appear in the summaries:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <div class="article-item">
            <h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
            <p>{{item.Description|striptags}}</p> {# 摘要只显示纯文本 #}
        </div>
    {% endfor %}
{% endarchiveList %}

If our article content uses a Markdown editor and renders it as HTML (for examplearchive.Content|render:trueThen the tag removal filter can also be applied to the rendered HTML content for further refinement control.

Summary

AnQiCMS template inremovetagsandstriptagsThe filter provides us with powerful content control capabilities. Whether it is necessary to completely remove all HTML tags to obtain plain text or to selectively remove specific tags to standardize content display, these filters are very practical tools. Combined|safeFilter, we can ensure that the content is both safe and rendered as expected.When using these tools, it is recommended to always perform thorough testing to ensure that the content display conforms to the design and functional requirements of the website.


Frequently Asked Questions (FAQ)

1.removetagsandstriptagsWhat are the differences between filters?

striptagsThe filter will remove all HTML tags from the HTML content, leaving only plain text. For example,"<b>Hello</b> World"|striptagsIt will output."Hello World"HoweverremovetagsThe filter allows you to specify one or more HTML tag names to remove only these specific tags while keeping the other tags and their content. For example,"<b>Hello</b> <i>World</i>"|removetags:"i"It will output."<b>Hello</b> World".

2. Why do I still need to add after usingremovetagsorstriptags?|safeFilter?

The AnQiCMS template system, to prevent cross-site scripting (XSS) attacks, defaults to escaping all output variable content. This means that HTML tags will be converted to&lt;and&gt;Entities such as, not parsed by the browser. When you useremovetagsorstriptagsif you want the remaining HTML content (such asremovetagsthat might be retained after<strong>Tags can be parsed by the browser normally, rather than displayed as raw HTML code, you need to use|safeThe filter explicitly tells the template engine that this content is safe and does not need to be escaped. If your goal is plain text, then instriptagsthen add|safeThe filter is a good habit, although it may not change the final visual effect for plain text output, it makes the process clearer.

**3.removetagsWhether the filter

Related articles

How to display the singular or plural form of a word based on the quantity value in the AnQiCMS template?

When building a website, we often encounter situations where we need to dynamically display text based on a certain quantity value.For example, when there is '1 comment', we want to display it in singular form; while for '2 comments', it should be displayed in plural form.This detail handling not only improves user experience but also shows the professionalism of the website content.If manual quantity judgment and writing if/else logic make the template code long and difficult to maintain.

2025-11-08

How to convert letter combinations like 'PONGO2' into the corresponding numbers on a phone keypad?

How to easily convert letter combinations to phone number keypad digits in AnQiCMS?In daily life, we sometimes encounter some phone numbers composed of letters and numbers, for example, some companies may use memorable numbers like "999-PONGO2" for brand promotion.However, when making a phone call in reality, these letters need to be converted into the corresponding numbers on the phone keypad.For website operators, if they can automatically complete this conversion on the website front end, it will undoubtedly greatly improve the user experience.

2025-11-08

How to dynamically define and use small array variables for loops in AnQiCMS templates?

In AnQiCMS template development, we often need to flexibly display some small data sets according to business logic.These collections may be some custom tags, navigation items, or just some status identifiers.Although AnQiCMS provides rich tags to call background data, sometimes we want to define a small array directly in the template and loop through it to achieve finer control and simpler template code.

2025-11-08

How does the AnQiCMS template automatically convert line breaks in text to HTML tags such as `<p>` or `<br>`?

In website content presentation, text formatting 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 newline characters (`\n`), and if it is displayed directly on the web page, the browser will not intelligently convert these newline characters into the HTML paragraph (`<p>`) or line break (`<br>`) tags we expect, causing the content to be cramped together and lose its original structure and readability.AnQiCMS (AnQiCMS) has fully considered this point in template design

2025-11-08

How to ensure that the multi-site content of AnQiCMS can be displayed and managed uniformly on the front-end?

In today's complex digital environment, many businesses and content creators often need to manage multiple websites, whether they have multiple brand sub-sites, different product line portals, or provide services for multilingual users.How can it be ensured that each site operates independently while also achieving unified display and efficient management of content on the front end, which has become a common challenge.AnQiCMS as an enterprise-level content management system, provides a powerful and flexible solution in this regard.

2025-11-08

How to customize the AnQiCMS content model to achieve personalized page content display?

AnQiCMS content management system provides us with powerful content management capabilities with its excellent flexibility and customizability.In the daily operation of websites, we often encounter situations where the standard "article" or "product" model cannot fully meet the needs of specific business scenarios.At this time, the custom content model feature of AnQiCMS is particularly important, as it allows us to build personalized content structures based on the unique needs of the website, thereby achieving more accurate and expressive display of page content.Why do we need a custom content model?

2025-11-08

How does AnQiCMS support the switching of multilingual content and the correct display on the front-end page?

AnQiCMS provides powerful multilingual support capabilities, helping websites easily meet the needs of global content promotion.Understand its working principle and configuration method, which can help you efficiently manage content in different languages and display it correctly on the front-end page. ### The Foundation of Multilingual Content Management: Multi-Site Mode One of the core ideas of AnQiCMS for implementing multilingual content switching is to make use of its powerful multi-site management function.This means, typically, you would create a separate site instance for each target language.

2025-11-08

How to optimize the display form of website URLs in search engines with the help of pseudo-static and 301 redirection functions?

In website operations, a clear, readable, and SEO-friendly URL structure is a key element in improving website visibility and user experience.AnQiCMS (AnQiCMS) knows this point, therefore it builds in these two important functions of pseudo static and 301 redirection, aiming to help users easily optimize the display form of the website in search engines, thereby bringing better ranking and traffic performance.

2025-11-08