What are the respective application scenarios of the `striptags` and `removetags` filters when cleaning HTML code in AnQiCMS templates?

Calendar 👁️ 74

In AnQiCMS template design, we often encounter situations where we need to clean up or simplify the HTML code in the content.This is not just for aesthetics, but also to ensure the correct display of content, improve page loading efficiency, and even prevent potential security risks.Secure CMS provides two very practical filters for this:striptagsandremovetagsAlthough they are all related to the removal of HTML tags, each has a clear applicable scenario.

striptagsFilter:Completely remove HTML tags and obtain plain text content.

When we want to completely extract the plain text part from a piece of content that contains HTML format,striptagsThe filter is particularly important. Its function is to strip all HTML, XML, and even PHP tags from the string, leaving only the text content, and it will also automatically clear HTML comments.

Application scenarios:

  1. Generate page meta description (Meta Description) or summary:Search engines usually only crawl plain text as metadata or content summaries for web pages.If the content source contains a large amount of complex HTML structure, directly extracting it may cause garbled text or unnecessary tag display.At this time, usestriptagsCan ensure that the output abstract is clean, concise pure text, which is beneficial for SEO optimization and user experience. For example, it is often used to display the article introduction on the article list page.
  2. Create plain text content preview:In some cases, such as in pop-ups, tooltips, or minimalist views on mobile devices, we may not need any formatting, just to display the skeleton information of the content.striptagsProvide this plain text view quickly.
  3. Output content to a non-HTML environment:If you need to export the website content to a text file, use it as the plain text part for generating email notifications, or provide plain text data to external systems via an API interface,striptagsEffectively remove all formats to ensure data compatibility.
  4. Clean up the 'dirty' content of user input:Although the AnQiCMS backend has a strict content filtering mechanism, in certain specific scenarios, if you want to perform an additional, thorough plain text conversion of user input,striptagsCan also act as an additional defense.

Example:Assumearticle.ContentContains a segment with<h2>/<p>/<strong>Tagged HTML content.

<meta name="description" content="{{ article.Content|striptags|truncatechars:150 }}">

<div class="article-summary">{{ article.Content|striptags|truncatewords:50 }}...</div>

BystriptagsAfter filtering, whether output tometaThe label, whether as an article summary, will be plain text without any HTML format.

removetagsFilter: Precisely remove the specified HTML tags while retaining the required format.

withstriptagsThe "No All" strategy is different,removetagsThe filter provides more refined control capabilities. It allows you to specify one or more HTML tags, and then only remove these specified tags from the content, while retaining all other HTML tags and content that are not mentioned.

Application scenarios:

  1. Content security filtering:This isremovetagsOne of the most common applications. To prevent cross-site scripting attacks (XSS), we may need to remove the user submitted content of the<script>/<iframe>/<style>Labels that have potential risks but are allowed to be retained<strong>/<em>/<a>Labels that are safe and commonly used.
  2. Unified content style:In different areas of the website, content may need to follow different style guidelines. For example, in the comment section, you may only allow users to use<strong>and<a>tags, while other like<img>or<h1>Tags need to be removed to keep the layout clean in the comment area.
  3. Content adapts to different display areas:Sometimes, the same content needs to be displayed in different sizes or styles. For example, the main content of a news article may include images and videos, but in the 'Hot Articles' list in the sidebar, we may want to remove all<img>and<video>Tags, only keep text and links to save space.
  4. Specific format adjustment:If the website's style design does not want some specific HTML tags (such as outdated tags)<font>Tags or irregular<span>appear at the front,removetagsCan accurately remove them without affecting the normal HTML structure.

Example:AssumeuserComment.ContentThe variable contains user submitted comments, which may include<strong>/<a>, but also has potential<script>and<img>.

<div class="comment-body">
    {{ userComment.Content|removetags:"script,style,iframe,img,video"|safe }}
</div>

Here, we removed<script>,<style>,<iframe>,<img>,<video>tags, but retained<strong>and<a>etc., safe and useful tags.|safeThe filter is necessary because it tells the template engine, after passing throughremovetagsThe remaining HTML code is safe and can be output directly as HTML without the need for default escaping.

How to choose: Ask yourself a question.

When deciding to usestriptagsOrremovetagsyou can ask yourself a simple question:I hope the content includes保留HTML format?

  • If the answer isNo, I just want plain text, not any HTML tagsThenstriptagsis your first choice.
  • If the answer isYes, I want to retain some HTML formatting, but delete specific tags that I do not want to appear.ThenremovetagsThat is a more suitable choice.

Understanding the core differences and application scenarios of these two filters can help us manage and display the content of the AnQiCMS website more efficiently and safely, making the template output more in line with expectations.


Frequently Asked Questions (FAQ)

Q1: I want to keep the content in<a>the link tags, but remove all other HTML tags, which filter should be used?

A1:In this case,removetagsThe filter is the better choice. You can explicitly specify to remove only<a>All common HTML tags outside of this, but this may be a very long list. A more direct approach is, if you clearly know except for<a>All tags outside should be removed, then you can first usestriptagsCompletely remove all tags to get plain text, then manually convert the URLs in the text to<a>Label (if your business logic allows it, or use suchurlizeauxiliary tools), but this is usually more complex. Usually, a more practical approach is to useremovetagsto clear those that are explicitly knownDon't wantthe label, and make sure you want to keep the label (such as<a>) is notremovetagsin the removal list. For example:{{ article.Content|removetags:"p,div,h1,h2,img,strong,em,script,style"|safe }}.

Q2:striptagsandremovetagsCan these two filters be used together?

A2:Can be used like a pipeline and connected. For example,{{ article.Content|striptags|removetags:"p" }}. However, due tostriptagsall HTML tags have been removed, and thenremovetagsthe operation is usually

Related articles

How to determine whether to truncate text and add an ellipsis (...) in AnQiCMS templates based on content length?

In AnQiCMS website content operation, how to elegantly handle long text content to make it both beautiful and complete on the page is the key to improving user experience.Especially on the list page, card display, or introduction area, overly long text often leads to layout confusion and affects the overall visual effect.AnQiCMS' powerful template engine provides various flexible ways to solve this problem, the most commonly used being the function of text truncation and adding ellipses.The AnQiCMS template system borrows the syntax of the Django template engine

2025-11-09

What is the default return value when the `integer` and `float` filters fail to convert in the AnQiCMS template?

When building a website on Anqi CMS, we often need to flexibly handle and display data in the template.These, `integer` and `float` filters are very commonly used tools when converting values to integers or floating-point numbers.However, have you ever thought about how the system will handle when these filters receive a value that cannot be recognized as a number?In other words, what default values will these filters return if the conversion operation fails?Understanding this is crucial for us to write robust and predictable template logic.###

2025-11-09

In AnQiCMS template, how to judge whether a string can be successfully converted to a numeric type and perform conditional processing?

In AnQi CMS template creation, we often encounter situations where we need to process strings entered by users or retrieved from the database.One common requirement is to determine whether a string can be successfully converted to a numeric type and to perform different conditional processing based on the result.This is crucial for data display, calculation, and even simple form validation.The AnQi CMS template engine (based on Go language's Pongo2) provides a rich set of filters (filters) and logical tags, allowing us to flexibly meet this requirement. Below

2025-11-09

In AnQiCMS template, how to judge and display the 'In stock' or 'Out of stock' status based on the product inventory (`Stock`) quantity?

It is crucial to clearly communicate the inventory status of products to users in website operations, especially for sites involving product display.This not only optimizes the user experience, reduces invalid consultations, but also effectively guides the user's purchase decision.AnQiCMS as a flexible and efficient content management system, implements the display of "in stock" or "out of stock" status according to the product inventory quantity in the template, which is very intuitive. AnQiCMS template system adopts a syntax similar to Django, which allows us to control the display of page content through concise tags and variables.When processing product information

2025-11-09

How can AnQiCMS templates safely display user-submitted rich text content to prevent potential XSS attacks?

During website operations, displaying rich text content submitted by users, such as article comments, forum posts, or blog content, is an unavoidable requirement.However, there may be malicious scripts hidden in these contents, and if they are displayed without precautions, it may lead to cross-site scripting (XSS) attacks, posing potential threats to website visitors.AnQiCMS (AnQiCMS) has fully considered this security risk in its design and provides a series of mechanisms through its template engine to help us safely handle this type of rich text content.

2025-11-09

How to control the automatic escaping of HTML tags with the `autoescape` tag in AnQiCMS templates?

In the AnQiCMS template system, our daily content display core is inseparable from the handling of HTML tags.To ensure the security of the website, AnQiCMS defaults to automatically escaping variables output in templates.This mechanism effectively prevents the injection of malicious code, such as common cross-site scripting attacks (XSS).However, in some scenarios, we may need to display rich text content that includes HTML tags, at this point we need to understand how to flexibly control this automatic escaping function.### Automatically Escaped

2025-11-09

How to check if the article content in the AnQiCMS template contains specific keywords and display conditions based on this?

In website content operation, we often need to flexibly adjust the display of the page according to the actual content of the article.For example, if an article mentions a specific product or event, we may want to highlight related purchase links or promotional information on the page;If the content of the article involves sensitive topics, it may be necessary to add additional disclaimers.This requirement for conditional display based on article content can be fully realized in the AnQiCMS template.AnQi CMS uses a template engine syntax similar to Django

2025-11-09

How to judge whether the current item is the first or last item in the `for` loop in AnQiCMS template?

In AnQiCMS template development, we often encounter situations where we need to display data in a list loop, such as article lists, product categories, navigation menus, etc.In these loops, sometimes we need to treat the first or last item in the list specially, such as adding unique CSS styles, displaying different content, or cleverly handling the separators between list items.AnQiCMS uses a syntax similar to the Django template engine, providing us with a very intuitive and powerful tool to solve these common template logic problems.### Core Mechanism

2025-11-09