How do the `removetags` and `striptags` filters remove specified or all HTML tags when processing HTML content?

Calendar 👁️ 74

In the daily content operation of Anqi CMS, we often encounter situations where we need to handle HTML content.In order to display plain text summaries in specific scenarios, or to standardize content output and enhance security, removing HTML tags is a common requirement.Aq CMS provides two very practical template filters for this:removetagsandstriptags. They each have unique uses and application scenarios, let's take a closer look at how they help us efficiently clean up HTML content.

striptagsFilter: One-click to clear all HTML tags

When our goal is to obtain a pure text without any formatting,striptagsThe filter is our powerful assistant. The function of this filter is very direct - it removes all HTML and XML tags from a piece of HTML content, leaving only the plain text between the tags.It will explicitly remove HTML comments, ensuring the output content is concise.

Imagine that you have published an article with a lot of paragraphs, images, links, and other HTML tags.Now, you need to display a brief summary of this content on the homepage or in search results, and this summary must be plain text without any HTML formatting to ensure uniform formatting.striptagsIt can be put to use.

Its usage is very simple, just pass the content to be processed through the pipe symbol|pass tostriptagsthe filter.

Usage example:

Suppose we have a piece of HTML content:<strong><i>Hello!</i></strong>

{# 移除所有HTML标签,并确保输出为HTML内容 #}
{{ "<strong><i>Hello!</i></strong>"|striptags|safe }}

The output of this code will be:Hello!

In practical applications,striptagsCommonly used in the following scenarios:

  • Generate plain text summaryGenerate a brief, unformatted summary for articles, product details, and content, for use on list pages, SEO descriptions (meta description), or in-site search results.
  • Text or email notification: Convert HTML content to plain text so that it can be sent as a text message or in an email that does not support HTML.
  • Clean up user submitted contentIn some input fields that do not require HTML (such as comment titles, message subjects), make sure that the user enters plain text to prevent unexpected format errors or potential security issues.

removetagsFilter: Precisely remove specified HTML tags

withstriptagsDifferent from the 'one-size-fits-all' approach,removetagsThe filter provides more refined control. It allows us to specify one or more HTML tags, and then only remove these specified tags from the content, while retaining other HTML tags that are not mentioned.This means we can selectively retain part of the format or structure according to specific needs.

For example, you may want to retain the bold<strong>and italic<em>effects, but at the same time want to remove all paragraphs<p>and hyperlinks<a>) tags.removetagsCan perfectly meet this requirement.

While usingremovetagsWhen, we need to pass the name of the tag to be removed as a parameter, separated by a comma,Separated, and passed to the filter.

Usage example:

Assuming we have a piece of HTML content:<strong><i>Hello!</i><span>AnQiCMS</span></strong>

  1. Remove a single tag:

    {# 移除<i>标签 #}
    {{ "<strong><i>Hello!</i></strong>"|removetags:"i"|safe }}
    

    The output will be:<strong>Hello!</strong>

  2. Remove multiple tags:

    {# 移除<i>和<span>标签 #}
    {{ "<strong><i>Hello!</i><span>AnQiCMS</span></strong>"|removetags:"i,span"|safe }}
    

    The output will be:<strong>Hello!</strong>

removetagsPractical scenarios include:

  • Standardize content structure: When content is imported from different sources, it may contain various irregular or redundant tags (such as too manydivorspanNested), it can be used toremovetagsSimplify it.
  • Local format control: When displaying content, it may be necessary to retain only the emphasis style of text (such as<strong>/<em>), and remove other layout-related tags (such astable/figure),to accommodate a specific display area.
  • Basic security filtering:Although it cannot completely replace professional HTML sanitization libraries,removetagsCan be used to remove common potentially dangerous tags from user input, such as<script>to reduce the risk of XSS (Cross-site Scripting) attacks. For example:{{ user_input|removetags:"script"|safe }}.

Choose the right tool:striptagswithremovetagsConsiderations for practical application

When choosing to usestriptagsOrremovetagsIt's all about your requirements for the final content format:

  • SelectstriptagsWhen you need absolute plain text output without retaining any HTML formatting.It is suitable for generating a concise preview of content, SEO metadata, or displaying content in environments that do not support HTML.
  • Selectremovetags: When you want to retain some specific format or structure of the content while removing other unnecessary tags.It is suitable for fine-tuning, trimming, or targeted security filtering of content.

about|safeImportant notes on the filter:It's worth noting that in the above examples, we usually do it after:striptagsorremovetagsthen use it immediately afterwards:|safeThe filter. This is because the Anqi CMS template engine, for security reasons, defaults to automatically escaping all HTML content to prevent XSS attacks. When we usestriptagsorremovetagsAfter processing the content, if the output still contains parts that we want to be parsed as HTML (such asremovetagsThe label is retained), or it is simply plain text, but we want to tell the template engine that it is already 'safe' content and does not need additional escaping, then we need to add|safeMake sure to explicitly tell the template engine: This content has been processed, it is safe, please parse it directly as HTML and do not perform additional HTML entity escaping. If not|safeEven if the tags are removed,<and>characters may also be escaped into&lt;and&gt;affecting the final display.

By mastering the use ofstriptagsandremovetagsThese powerful filters allow us to manage the HTML content on the Anqi CMS website more flexibly and efficiently, whether for aesthetics, compatibility, or security, we can find appropriate solutions.


Frequently Asked Questions (FAQ)

1. Why did I usestriptagsorremovetagsAfter, the content in<or>was escaped into&lt;and&gt;?This is usually because the template engine of AnQi CMS defaults to automatically escaping all output HTML content for security reasons to prevent cross-site scripting (XSS) attacks.Even if you remove the tags, if the remaining content contains HTML special characters, they may also be escaped.To ensure that after passing throughstriptagsorremovetagsThe processed content (especially those HTML fragments you want to be displayed as intended by the browser) should be displayed as expected, you need to add it at the end of the filter chain|safe.|safeThe filter tells the template engine that this content is safe and can be directly output as HTML without escaping.

2.removetagsCan you remove the JavaScript code? For example<script>Tag?Yes,removetags:"script"Can you effectively remove the content within<script>Tag and the JavaScript code inside it.This can be used as a primary means to prevent XSS attacks to some extent.However, it is important to note that XSS attacks come in many forms, not limited to<script>Tags, and may also be injected through HTML attributes (such asonerror/onloadetc). Therefore,removetagsAlthough useful, it cannot completely replace professional, more comprehensive HTML content purification libraries or backend security filtering mechanisms.For scenarios involving HTML in user input, it is recommended to combine multi-layer security strategies.

3.striptagsWill it remove HTML entities (such as )? striptagsThe main goal is to remove HTML tags (such as<p>/<a>/<div>), it usually does not remove HTML entities (such as representing non-breaking spaces,&amp;Indicates&Symbol,&lt;Indicates<Symbols). These entities are retained because they represent part of the text content, rather than structure or format tags.If you need to remove HTML entities from text, you may need to combine other custom text processing methods or regular expressions to achieve this.

Related articles

How to use the `random` filter in Anqie CMS template to randomly return a character or value from a string or array?

In AnQi CMS template development, sometimes we hope to add a touch of dynamism and surprise to the website content, so that visitors can see different elements each time they refresh the page.This is a very practical tool, the `random` filter.It can help us randomly select one from a set of predefined data to display, whether it is randomly selecting characters from a string or randomly selecting a value from an array (or list), it can be easily achieved.

2025-11-08

How does the `phone2numeric` filter convert letters on a mobile phone's numeric keypad to the corresponding numbers?

In AnQiCMS template development, we often need to handle various data, and sometimes we may encounter some special situations with phone number input and display.For example, some phone numbers include letters (also known as "pretty numbers" or "vanity numbers", such as 1-800-FLOWERS) for ease of memorization or brand promotion.However, when dialing in practice, these letters need to be converted to the numbers on the corresponding number keypad.AnQiCMS provides a very practical built-in filter——`phone2numeric`, which helps us easily complete this conversion

2025-11-08

How to define a string array variable directly in the template using the `list` filter?

AnQiCMS with its flexible and powerful template engine, provides great convenience for content display.When using templates for front-end development, we often need to handle various data, among which array variables are a common and practical data structure.Most of the time, we may need to define some fixed or temporary string arrays directly in the template, rather than passing them through backend code each time.Fortunately, AnQiCMS provides a very convenient `list` filter, making this operation extremely simple.### Core Function Analysis: `list`

2025-11-08

How does the `linenumbers` filter add line number markers to each line of multiline text?

In website content display, sometimes we need to add line numbers to specific multi-line text content, such as code examples, step-by-step tutorials, or log information, to enhance readability and facilitate reference.AnQiCMS provides a simple and practical template filter `linenumbers`, which can help us easily achieve this function. ### The `linenumbers` filter's purpose The `linenumbers` filter is specifically used to automatically add line number markers to each line of multi-line text.It will start from the number 1

2025-11-08

How does the `repeat` filter output a string repeated a specified number of times?

During the process of website content creation, there are times when we have the need to output a specific string multiple times, such as for visual separation, placeholder content, and quick generation of list items.In the AnQiCMS template system, the `repeat` filter provides a very practical function that can help us complete this task efficiently.This filter, as the name implies, repeats a string according to the number we specify, thus saving the trouble of manual copying and pasting, greatly enhancing the efficiency and flexibility of template writing.###

2025-11-08

How to search and replace specific keywords in the `replace` filter of the Anqi CMS template?

In the daily content management and template design of AnQi CMS, we often encounter scenarios where we need to search and replace specific content in strings.Whether it is to unify brand names, filter sensitive words, or adjust the display format of some text, manually modifying a large amount of content is undoubtedly cumbersome and inefficient.Fortunately, AnQi CMS provides a very practical template filter——`replace`, which can help us easily implement these string operations.### `replace` filter

2025-11-08

How to slice a string or array elements within a specified range using the `slice` filter?

The AnQiCMS template engine provides rich filters, giving you great flexibility in displaying content.Among them, the `slice` filter is a very practical tool that can help you accurately extract elements within a specified range of strings or arrays, whether you want to display an article summary, limit the number of images, or handle other data segments, it can be very useful.### The working principle of the `slice` filter The syntax of the `slice` filter is concise and clear: `{{ obj|slice:"from:to" }}`

2025-11-08

How `split` and `make_list` filters split a string into an array by a specified delimiter or character?

In Anqi CMS template development, flexibly handling string data is an indispensable skill for building dynamic pages.Sometimes, we need to split a long string into a data list using a specified character or string as a delimiter (which is what we commonly call an array);At other times, we may need to process each character of the string independently.AnQi CMS provides two very practical filters: `split` and `make_list`, which can help us easily meet these needs.###

2025-11-08