How to implement `striptags` and `removetags` filters in Anqicms, one for removing all HTML tags and another for removing specified tags?

Calendar 👁️ 75

Managing content in Anqi CMS, we often encounter scenarios where we need to handle HTML tags.To ensure the purity of content, meet display requirements, or ensure safety, it is an important ability to flexibly control HTML tags.AnQi CMS provides a powerful template enginestriptagsandremovetagsThese are very useful filters that can help us easily remove all HTML tags or remove specified tags.

We will delve into how these two filters work together and how to maximize their value in practical applications.

Remove all HTML tags:striptagsFilter

Imagine you have a piece of content copied and pasted from an external source, which includes various complex HTML tags, such as<div>/<span>/<p>/<strong>/<i>Even some style tags that should not appear. If these contents are displayed directly, it may destroy the overall layout and style of your website. At this time,striptagsThe filter comes into play.

striptagsThe filter works very directly and thoroughly: it strips all HTML, XML, and even PHP tags from a string, including HTML comments.Its goal is to provide the purest text content.

When to usestriptags?

  • Generate a content summary or abstract:On the article list page, you may only want to display the plain text summary of the article, without any images or complex layouts. UsestriptagsIt can ensure that the generated summary is clean and tidy.
  • Create plain text export:If you need to export content as plain text or for an RSS feed,striptagsit is a good choice.
  • Handle untrusted external content:Although the template engine of AnqieCMS defaults to escaping output to prevent XSS attacks, if your content source is very complex and unreliable, an additional usestriptagsCan provide an additional layer of protection, ensuring that no potential malicious script tags are rendered.

How to usestriptags?

Its usage is very simple, just need to pass the variables to be processed through a pipeline symbol.|Connected tostriptagsthe filter.

Assuming we have a variablearticleContentIts value is<strong><i>Hello 安企CMS!</i></strong><p>这是一个测试段落。</p>.

If you want to remove all HTML tags and only keep plain text, you can write it like this:

{# 假设 articleContent 变量包含 HTML 内容 #}
<div>原文:{{ articleContent|safe }}</div>
<div>清除所有标签后:{{ articleContent|striptags|safe }}</div>

In this example,articleContentafterstriptagsAfter processing, the output will beHello 安企CMS!这是一个测试段落。. It should be noted that in order to see the actual effect of the filter removing tags in the browser, we have added to both the original output and the processed output.|safeFilter to avoid the default HTML escaping mechanism of the Anqi CMS template engine displaying the tag itself as an entity character.

Precisely remove the specified tag:removetagsFilter

Sometimes, we do not want to remove all HTML tags, but rather want to preserve most of the formatting, removing only some specific tags that we do not want to appear. For example, you may want to preserve paragraphs.pand listul/litags, but remove allfonttags and inlinestyleproperties to ensure that the content style is controlled by the CSS of your website. At this point,removetagsthe filter can provide this fine control.

removetagsThe filter allows you to specify one or more HTML tag names, which will precisely remove these tags and their contents from the string (if the tag is self-closing, such as<img>If it is a single tag, such as<strong>If it is a paired tag, such as

When to useremovetags?

  • Standardize the content format:When you import content from different sources and find that certain HTML tags (such as<span>/<b>/<font>) are misused, leading to inconsistent styles,removetagsit can help you clean up in bulk.
  • Optimize content semantics:For example, some outdated HTML tags,<i>May no longer be recommended in terms of semantics. If you want the content to be more in line with modern Web standards, you can remove them while retaining the enclosed text.
  • Clean up external references:If your content often includes references from other websites, it may contain unnecessary or problematic tags, you can useremovetagsSelective cleaning.

How to useremovetags?

UseremovetagsWhen,you need to pass the name of the tag you want to remove as a parameter to the filter.If multiple tags are to be removed,they can be separated by a comma.,Separate them.

Continue to usearticleContentVariable:<strong><i>Hello 安企CMS!</i></strong><p>这是一个测试段落。</p>

  1. Remove a single tag:Suppose we only want to remove<i>Labels, but retain<strong>andpTags:

    <div>移除<i>标签后:{{ articleContent|removetags:"i"|safe }}</div>
    

    The output will be<strong>Hello 安企CMS!</strong><p>这是一个测试段落。</p>

  2. Remove multiple labels:Suppose we want to remove simultaneously<i>Tags and<strong>Tags:

    <div>移除<i>和<strong>标签后:{{ articleContent|removetags:"i,strong"|safe }}</div>
    

    The output will beHello 安企CMS! <p>这是一个测试段落。</p>

By this means,removetagsThe filter gives us great flexibility, allowing us to precisely remove unnecessary HTML elements while retaining the required format.

Summary and Application Scenarios

striptagsandremovetagsThey are all powerful tools for handling HTML tags in Anqi CMS template engines, but their application scenarios are somewhat focused.

  • When you needCompletely strip all HTML formatsWhen only plain text is retained, for example, when generating article summaries, creating plain text export content, or when strictly purifying content, the option to choosestriptags.
  • When you needSelectively remove specific HTML tagsWhen choosing to preserve other structures and styles, such as standardizing the format of imported content, removing old tags that do not conform to semantics, or cleaning up specific interfering elements, selectremovetags.

In daily content operation, understanding and skillfully using these two filters will enable you to manage and display content more effectively, ensuring the cleanliness, consistency, and security of the website.


Frequently Asked Questions (FAQ)

1. Why do I sometimes usestriptagsorremovetagsa filter, but the browser still shows HTML tags, such as&lt;p&gt;instead of an actual paragraph?

This is usually because the AnQiCMS template engine defaults to escaping all output content to prevent XSS attacks. When your variable is already an escaped HTML entity (for example, the content is already&lt;p&gt;), or you have not explicitly declared the content to be safe after using the filter (|safe), the template engine will escape it again. In order tostriptagsorremovetagsCan correctly identify and handle HTML tags, you need to ensure that the content provided to them is the original HTML string, and in the final display, if you want the browser to render HTML tags instead of displaying entity characters, you need to add an extra|safea filter. For example:{{ archive.Content|removetags:"p"|safe }}.

2. In addition to these two filters, what built-in features does Anqicms have in terms of content security to prevent malicious HTML code (such as XSS attacks)?

AnQi CMS attaches great importance to content security. In addition,striptagsandremovetagsIn addition to content cleaning on the front-end template level, the system also has multiple built-in security mechanisms.The most fundamental and important thing is that, by default, the template engine of Anqi CMS will automatically escape all HTML tags output from the background to the front end.This means, even if it includes<script>such malicious tags, they are usually also converted to&lt;script&gt;Entities are used to prevent execution. In addition, the Anqi CMS backend also provides content security management, sensitive word filtering, and other functions to review and clean content from the source, further reducing security risks.

3. If I want to remove most of the HTML tags but also want to keep the images<img>and links<a>How should I operate?

In this case,removetagsThe filter is your **choice. You can list all the tags you want to remove, but deliberately excludeimgandatags. For example, if you want to removep/strong/iBut retain labels, images, and links, and it can be written like this:{{ article.Content|removetags:"p,strong,i,span,div"|safe }}So, except for the labels you specify explicitly, they will be removed,<img>and<a>Tags and their attributes will be preserved. If you need further style or behavior control for images and links,

Related articles

How to use the `yesno` filter to output custom text such as 'Enabled/Disabled/Pending' based on the boolean value or the existence of a field returned by the Anqi CMS backend?

In website operation, we often need to display corresponding text prompts on the front page according to the status of the content, such as whether it is enabled, recommended, or online.Directly outputting the boolean value `true` or `false` returned by the backend may not be intuitive and friendly.The AnQiCMS template engine provides a simple yet powerful tool - the `yesno` filter, which can help us elegantly convert boolean values or field existence states into easily understandable custom text, such as "Enabled/Disabled/Pending"}

2025-11-08

The `addslashes` filter in AnQi CMS, how to escape a string that may contain special characters to safely insert into JS or HTML attribute values?

In the daily operation of Anqi CMS, we often need to display the dynamic content stored in the database on the front end of the website.This content may come from user input, data scraping, or other channels, and it is inevitable that it will contain some special characters.If these special characters are not handled properly and directly inserted into JavaScript code or HTML attribute values, it may cause page layout chaos, functionality failure, and even serious security risks, such as cross-site scripting attacks (XSS).

2025-11-08

How does the `add` filter in the Anqi CMS template implement the mixing of numbers and strings and how to handle type mismatches?

AnQiCMS (AnQiCMS) provides flexible and powerful tools for content creators and website developers with its Django-like template engine syntax.When building dynamic web content, we often need to combine different types of data (such as numbers and strings) together to form the final display effect.At this time, the `add` filter in the Anqi CMS template can come in handy.

2025-11-08

How to efficiently remove specific punctuation marks or spaces from a string using the `cut` filter in the Anqi CMS template to clean up the output content?

In the daily operation of AnQi CMS, we often encounter situations where we need to refine the content output by templates.To make the page display cleaner, improve the user reading experience, or generate URLs that are more beneficial for SEO, removing unnecessary punctuation or extra spaces from strings is a very practical skill.The powerful template engine of Anqi CMS provides a rich set of filters to help us achieve these goals, among which, the `cut` filter is a simple yet extremely efficient tool.### `cut` filter

2025-11-08

In Anqi CMS template, how does the `random` filter implement the random selection of an element from an array or string to display and enhance the dynamic nature of the content?

Make the Anqi CMS website content vivid: explore the `random` filter, and uncover the mystery of dynamic display In the era of information explosion, an efficient and flexible website content management system is an indispensable tool for operators.The AnQi CMS is a system developed based on the Go language, dedicated to providing a high-performance, easily scalable content management solution. It uses a syntax similar to the Django template engine in template design, greatly simplifying the complexity of development and content presentation.But besides content publishing, we all hope that the website can maintain its freshness

2025-11-08

How to use the `first` and `last` filters to quickly get the title of the first or last article in the Anqi CMS article list?

In website operation, we often need to quickly extract some specific information from the article list, such as the homepage may need to display the latest article title, or in some special modules, it is necessary to obtain the title of the first or last entry in the article list.AnQiCMS (AnQiCMS) can easily meet these needs with its flexible template engine and rich filter functions.AnqiCMS's template system draws on the syntax of mainstream template engines like Django

2025-11-08

What are the application scenarios and encoding differences of the `urlencode` and `iriencode` filters in the AnQi CMS template when encoding URL parameters?

In AnQiCMS template development, when handling URL parameters, we often encounter the need to encode them.This is mainly to ensure the legality of the URL, avoid special characters from destroying the URL structure, and correctly transmit data containing non-ASCII characters (such as Chinese).AnQiCMS provides the `urlencode` and `iriencode` filters to help us complete this task, but their application scenarios and encoding differences are not the same.

2025-11-08

How to use the `linebreaks` and `linebreaksbr` filters to convert newline characters in the plain text content entered by an Anqie CMS user into HTML `<p>` or `<br>` tags?

In a content management system, processing plain text content entered by users and displaying it on the web page in the expected format is a common requirement.When the user enters text with line breaks in the back-end editor, the browser does not default to rendering it as HTML line breaks.All content may be squeezed onto one line, causing disordered layout and affecting reading experience.Fortunately, AnQiCMS provides a convenient template filter to solve this problem.

2025-11-08