How to use the filter (filter) to truncate, convert case, or escape HTML in displayed text?

Calendar 👁️ 74

When building a website, we often need to process various types of text content displayed on the page, such as limiting the length of article summaries, unifying the case format of user input, or ensuring that user-submitted content can be safely displayed on the page without destroying the page structure.AnQiCMS (AnQiCMS) provides us with powerful template filter functions, which can efficiently and conveniently complete these tasks.

The filter is a very practical tool in the Anqi CMS template, which can help us quickly process and format the data displayed on the page. Its usage is very intuitive, usually by adding a pipe symbol after the variable name|Then follow the name of the filter and optional parameters. For example,{{ 变量名|过滤器名称:参数 }}Now, let's take a detailed look at several commonly used text processing filters.

Text truncation: Make long content more concise

In website operation, we often need to display an abstract of multiple contents on a single page, such as article lists or product introductions.At this time, if the content is too long, it not only affects the beauty of the page, but also reduces the efficiency of user browsing.The text truncation filter of AnQi CMS can help us easily solve this problem.

first, truncatecharsThe filter can truncate text based on the specified number of characters. It counts from the beginning of the text and truncates after reaching the specified character count, adding an ellipsis at the end....For example, if we have a text "AnQi CMS is an enterprise-level content management system developed based on the Go language, committed to providing an efficient, customizable, and scalable content management solution.Please only display the first 15 characters, we can use it like this: {{ item.Description|truncatechars:15 }}The output will be "AnQi CMS is a Go-based...". It should be noted that,truncatecharsWhen truncating, word integrity will not be considered, and it may result in half a word being truncated.

withtruncatecharssimilar,truncatewordsThe filter truncates based on the number of words. It counts the number of words in the text and then truncates to the specified number of words, adding an ellipsis at the end. For example,{{ item.Description|truncatewords:5 }}It may output "Anqi CMS is a Go language-based..." This filter is more suitable for English content as it better maintains word integrity.

When processing rich text content that includes HTML tags, directly usetruncatecharsortruncatewordsIt may damage the HTML structure, causing the page to display abnormally. To avoid this situation, Anqi CMS provides a specialtruncatechars_htmlandtruncatewords_htmlFilter. These filters will close HTML tags intelligently while truncating text, ensuring that the truncated HTML content remains valid.This is very useful for displaying article summaries or user comments and rich text content, as it can avoid page chaos caused by truncation.

Case conversion: standardize the text format

In certain scenarios, we need to standardize the case format of text, such as converting all user input to title case or capitalizing titles to emphasize them.The case conversion filter of AnQi CMS can meet these needs.

upperThe filter can convert all English characters in the text to uppercase. For example,{{ item.Title|upper }}It will convert "anqicms template" to "ANQICMS TEMPLATE".

On the contrary,lowerThe filter can convert all English characters to lowercase.{{ item.Title|lower }}It will convert “ANQICMS TEMPLATE” to “anqicms template”.

If we only need to capitalize the first letter of a string, we can usecapfirstFilter. For example,{{ item.Introduction|capfirst }}It will convert 'anqicms is dedicated to providing efficient' to 'Anqicms is dedicated to providing efficient'.

AndtitleThe filter is more suitable for title-like content, it will capitalize the first letter of each word in the text.{{ item.Name|title }}It will convert "anqicms is awesome" to "Anqicms Is Awesome".These filters help us maintain consistency and professionalism in the formatting of multilingual content, especially English content.

HTML escaping and unescaping: Ensuring content safety and display effects.

In web development, security is a very important consideration when handling user input content.To prevent cross-site scripting attacks (XSS), AnQiCMS defaults to escaping variables output in templates.This means, if the variable contains</>/&Special characters are automatically converted to HTML entities (such as&lt;/&gt;/&amp;), thus preventing the browser from interpreting them as actual HTML tags or scripts.

In most cases, we do not need to use explicitlyescapeorefilters because AnQiCMS has already handled it by default. However, if we areautoescape offin the environment, or you need to explicitly escape a variable, you can useescapeor its abbreviationeFor example,{{ "<script>alert('xss');</script>"|e }}will convert malicious scripts into harmless text for display.

But sometimes, we need to display on the page the trusted content generated by a rich text editor, which includes HTML tags, and we want these HTML tags to be parsed and rendered by the browser in style, rather than displayed as source code. In this case, we need to usesafefilter.safeThe filter will inform AnQiCMS that the content of this variable is safe, no HTML escaping is needed, and the original HTML can be output directly. For example, ifitem.ContentVariables contain<p>这是<b>加粗</b>的文字</p>, directly{{ item.Content }}It will display the source code by default, but using{{ item.Content|safe }}After that, the page will display styled text normally.

It is worth emphasizing that usingsafeUse filters with caution. Only use them when you fully trust the source and are certain they do not contain any malicious code to prevent potential security risks.If you want to control the escaping behavior of the entire module block, you can useautoescapetags, through{% autoescape on %}or{% autoescape off %}to turn on or off automatic escaping.

Practical skills and precautions

The filter function of Anqi CMS is very flexible, we can use multiple filters in series to form a processing chain. For example, if you want to convert a piece of text to lowercase first and then truncate it to a specified number of characters, you can write it like this:{{ item.Title|lower|truncatechars:20 }}The filter will execute in order from left to right.

It is very important to understand whether the filters accept parameters (such as truncation length, case conversion type, etc.) when using them. Parameters are usually specified through a colon:Connect after the filter name. We also need to understand the type of the variable itself to ensure that the correct filter is used and unnecessary errors are avoided.

These template filters greatly enhance the ability of AnQi CMS template to process data, making content operation and website development more efficient.By flexibly using them, we can better control the way content is presented, enhance user experience, and ensure website security.


Frequently Asked Questions (FAQ)

  1. Why does the HTML content I output in the template, such as images or links added through a rich text editor, display as code directly instead of the normal style? Answer:This is usually because the AnQi CMS, for security reasons, defaults to HTML-encoding all output variables, to<Translate special characters to&lt;This causes the browser to recognize it as plain text. If you are sure that this HTML content is safe and you want it to be rendered normally, please add it to the variable after|safeFilter, for example{{ item.Content|safe }}.

  2. Question: I usetruncatecharsThe filter truncated a piece of text but found that the HTML tags were broken, causing the page to display chaos. How should this be resolved? Answer:Do not use when you need to truncate rich text content containing HTML tagstruncatecharsortruncatewordsPlease use insteadtruncatechars_htmlortruncatewords_htmlFilter. These two filters will intelligently handle HTML tags, ensuring proper closure of tags while truncating to avoid damaging the page structure.

  3. Ask: Can I use multiple filters on a variable at the same time? What is the execution order? Answer:Yes, AnQi CMS supports using multiple filters for the same variable, separated by a pipe symbol.|Connecting. The execution order of filters is from left to right. For example,{{ item.Title|lower|truncatechars:10 }}Will first convert the title to lowercase and then truncate it to 10 characters.

Related articles

How to perform simple arithmetic operations such as addition, subtraction, multiplication, and division in AnQiCMS templates?

When creating templates in AnQiCMS, we often need to perform some simple numerical calculations, such as displaying the total price of goods, calculating the percentage of article reading volume, or handling the serial numbers in the list.AnQiCMS is a powerful template engine that supports direct arithmetic operations such as addition, subtraction, multiplication, and division in templates, making our content display more flexible and dynamic.

2025-11-08

How to display a list of related documents on the document detail page, such as categorized recommendations or keyword-based recommendations?

In website content operation, providing more relevant and potentially interesting content to visitors is a key strategy to enhance user experience, extend website stay time, and promote in-depth content browsing.This not only effectively guides users to explore more information, but is also an important component of 'inter-page relevance' in Search Engine Optimization (SEO).In such a powerful content management system as AnQiCMS, it is easy and efficient to implement the display of related document lists on the document detail page.

2025-11-08

How to display the link and title of the previous and next article in AnQiCMS template?

It is crucial to provide visitors with a smooth navigation experience in website operation.When a user finishes reading an article, they naturally expect to find more related content, and the "Previous" and "Next" links are the key features to meet this need.They can not only improve the user's stay time on your website, but also have a positive impact on search engine optimization (SEO) by building an internal link structure.AnQiCMS provides concise and efficient built-in tags for template developers, allowing you to easily display links and titles of the previous and next articles on the article detail page.

2025-11-08

How to implement filtering in the article list based on custom parameters (such as product features, price range)?

In website operation, we often need to classify and filter content lists more finely to help users quickly find the information they are really interested in.Traditional article classification can solve most problems, but when the content attributes become more complex, such as products with multiple characteristics, price ranges, or events with different themes and participation methods, a single classification seems to be inadequate.

2025-11-08

How to display a preset default value (such as "No data") for empty variables in the template?

In website operation, the completeness of content display and user experience is crucial.When we call data in AnQiCMS (AnQiCMS) template, we sometimes encounter the situation where some variables are empty.If these empty variables are not processed, the front-end page may appear blank areas, 'null' text, and even cause layout disorder, thus affecting the professionalism of the website and the user's browsing experience.

2025-11-08

How to convert multi-line text (including newline characters) in a template to an HTML paragraph or `<br/>` tag for display?

In website content operation, we often encounter such situations: the background text input box allows users to enter multiple lines of text, such as article summaries, product descriptions, contact addresses, and so on.When these multi-line text containing line breaks are displayed in a website front-end template, if output directly, we will find that the original line breaks do not take effect, and all the text is squeezed into one line.This is because the browser defaults to merging consecutive whitespace characters (including newline characters) into a single space.

2025-11-08

How to automatically identify and convert URL strings in text to clickable HTML links?

Bring URLs to life in text: The Practical Guide to Automatic Link Conversion in Anqi CMS In daily website content operations, we often encounter situations where a large number of web links are included in the text content copied and pasted from various sources.These links, if only existing in plain text form, not only cannot be clicked to jump, affecting user experience, but also cause potential traffic and information transmission opportunities to be lost in vain.

2025-11-08

How to safely display content containing HTML tags or JavaScript code in a template and prevent XSS attacks?

Building website templates in AnQiCMS (AnQiCMS), ensuring the safe display of content is a core issue, especially when the content may contain HTML tags or JavaScript code, how to effectively prevent cross-site scripting (XSS) attacks is particularly important.AnQi CMS is a Go language content management system that focuses on security and considered these security challenges from the outset, providing mechanisms to help users manage and control the rendering of content.

2025-11-08