How to process and display variable content through filters (such as `truncatechars`, `safe`)?

Calendar 👁️ 67

Optimize content display: Application of variable filter in AnQi CMS

How to present information accurately and beautifully in website content management is the key to improving user experience.AnQi CMS is a flexible and efficient content management system that provides a powerful template engine, allowing us to refine and display variable content through various filters, thus better meeting the needs of page layout and information delivery.These filters are like the 'makeup artists' of content, allowing the original data to be displayed in the most appropriate form.

The Anqi CMS template engine uses syntax similar to Django, which means we can make full use of the rich filtering functions when processing variables in the template. A variable is usually enclosed in double curly braces{{ 变量名 }}Output. And when we need to process this variable, we just add a pipe symbol after it|Add the name of the filter, and if the filter requires parameters, use a colon.:Separator. For example,{{ 变量名 | 过滤器名称 : 参数 }}. This concise syntax makes dynamic content processing easy.

Simplified text:truncatecharsandtruncatechars_html

Imagine you have a list of articles, each with a long description. Displaying them directly might make the page look disorganized. At this point,truncatecharsThe filter can be put to good use. It can truncate the string to a specified number of characters and automatically add an ellipsis at the end (...)。This is very useful for creating content summaries or fixed-length titles.

For example, if you want the description of the article to show only the first 50 characters:{{ item.Description | truncatechars:50 }}This way, even if the original description is long, only 50 characters and an ellipsis will be displayed on the page, maintaining the page's neatness.

It should be noted that,truncatecharsIs for plain text. If your description content contains HTML tags (such as rich text editor generated content), use it directlytruncatecharsMay destroy the HTML structure. Anqi CMS providestruncatechars_htmlFilter. It truncates text while intelligently handling HTML tags to ensure the output HTML remains valid.It is particularly important to handle rich text summaries that include images, links, etc.

Safe output:safeThe importance of the filter

In web development, content security is always of paramount importance, especially when the content comes from user input or rich text editors.Unprocessed HTML or JavaScript code can lead to cross-site scripting (XSS) attacks.The template engine of AnQi CMS defaults to HTML-escaping all output content, that is, <to&lt;,>to&gt;etc., thereby effectively preventing the execution of malicious code.

However, in some cases, we indeed need to display the original HTML content, such as the main text of articles, formatted content generated by rich text editors, etc. At this time,safeThe filter becomes crucial. By adding after the variable|safeWe can tell the template engine that the current output content is 'safe', and it does not need to be HTML escaped. It can be rendered directly as HTML code.

For example, when displaying the article text:{{ archive.Content | safe }}This ensures that the title, paragraphs, images, and other HTML elements in the article can be displayed normally and not treated as plain text. But please note that you should only use it when you are sure that the content is reliable and does not contain malicious scripts.safeFilter. Use caution or additional cleaning for unreviewed content submitted by users.

List of other practical filters.

In addition to the two commonly used filters mentioned above, AnQi CMS also provides many other convenient content processing filters:

  • default: Set a default value for a variable. If the variable is empty or does not exist, it will display the default value you specified, to avoid the page from appearing blank or with errors.{{ userName | default:"匿名用户" }}
  • stampToDate: Format the timestamp into a readable date and time. Anqicms also provides a template function to handle 10-digit timestamps and supports Golang's time format string.{{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}
  • upper/lower/title: Used to adjust the case of text.upperConvert to uppercase,lowerConvert to lowercase,titleThen capitalize the first letter of each word.{{ item.Title | upper }}
  • striptags/removetags: is used to remove HTML tags from text.striptagsRemove all HTML tags,removetagsCan specify the removal of specific HTML tags.{{ item.Description | striptags }}
  • addUsed to connect strings or add numbers.{{ "商品数量:" | add:item.Quantity }}
  • urlizeAutomatically identify URLs or email addresses in text and convert them into clickable hyperlinks. This is very useful for automatically generating links in comments or messages.{{ comment.Content | urlize | safe }}

Flexible combination and practice

The Anqi CMS filter can be chained, which means you can apply multiple filters to a variable consecutively, with the processing order from left to right. For example:{{ item.Content | striptags | truncatechars:100 | safe }}This code will first remove HTML tags, then truncate to 100 characters, and finally output safely. This combination capability makes content processing very flexible and powerful.

In practical operation, reasonably using these filters can greatly enhance the presentation quality and maintenance efficiency of website content. Prioritize limiting the length of fields such as titles and abstracts.truncatecharsortruncatewordsand its HTML variant. For rich text content, such as article details, it is essential to usesafeBut make sure the content source is secure. Through continuous practice and exploration, you will find that the filter of AnQi CMS is an indispensable tool for content operation.


Frequently Asked Questions (FAQ)

  1. Why do I usetruncatecharsWhen truncating content containing HTML, the page displays an error? AnswerThis is becausetruncatecharsThe filter is for truncating plain text, it does not intelligently recognize and handle HTML tags.When an HTML tag is truncated, it may cause the tag to be unpaired, thereby destroying the page structure.In this case, you should usetruncatechars_htmlA filter that can safely truncate text containing HTML while maintaining the integrity of the HTML structure.

  2. Question:safeFilters andautoescape offWhat is the difference between tags? Which one should I use? Answer:safeThe filter acts on a single variable, it tells the template engine not to escape the output content of the specific variable.autoescape offThe tag is applied to a template code block, which disables the automatic HTML escaping of all variable outputs within the code block. It is generally recommended to usesafeA filter because it has a smaller scope, allowing for more precise control over what content is not escaped, reducing security risks. Only consider using it when you are very sure that the entire content of the code block does not require escaping.autoescape off.

  3. Ask: Can I use a custom filter? What custom methods does Anqi CMS support? Answer: Anqi CMS is developed based on Go language, and its template engine supports expansion.Although the document does not directly explain how users can add custom filters through the backend interface or simple configuration, but as a customizable and easily expandable system, this usually means that you can register new filter functions by modifying or writing Go language code.For ordinary operators, it is recommended to prioritize the use of the rich filters built into the system to meet their needs.If there is a special business requirement, you can consult the developer or refer to the more in-depth secondary development document.

Related articles

How to use for loop to traverse list data in the template and display it?

In website content management, dynamically displaying list data is a very basic and important function.Whether it is a news list, product display, category navigation, or friend links, we need to be able to flexibly obtain data from the backend and present it on the frontend template.AnQiCMS (AnQiCMS) provides a powerful and easy-to-use template engine that allows us to easily meet these requirements, among which the 'for loop' is the core tool for displaying list data.AnQiCMS's template engine adopts a syntax style similar to Django

2025-11-08

How to dynamically control the display of content in the template based on conditional logic (if/else)

In AnQiCMS template design, it is possible to flexibly control the display of content based on different conditions, which is the key to achieving website personalization and dynamic display.Whether it is to decide whether to display the picture according to whether the article has a thumbnail, or to display specific content based on the user's role, conditional logic can provide strong support.AnQiCMS uses a syntax similar to the Django template engine, which makes it very easy for webmasters familiar with web development to get started quickly.### Master the basic conditional logic in AnQiCMS templates AnQiCMS

2025-11-08

How to display copyright information and link to the record number at the bottom of the website?

Clearly display copyright information and filing number at the bottom of your website, which is not only a legal requirement but also a key factor in enhancing the professionalism and user trust of the website.AnQi CMS as an efficient content management system, fully considers these details, allowing you to easily manage and present these important site information. ### Understanding the Importance of Copyright Information and Filing Numbers The copyright statement at the bottom of the website, like a brand watermark, clearly identifies the ownership of the content to visitors, effectively protecting your original achievements.As for websites operating in mainland China

2025-11-08

How to retrieve and display the Logo, thumbnail, and slideshow group on a single page?

In Anqi CMS, single pages (such as "About Us", "Contact Us", etc.) can not only carry rich text information but also greatly enhance the attractiveness and professionalism of the page through visual elements.Retrieve and display the Logo, thumbnail, and slideshow group on a single page, which is a key step to optimize the page display effect.AnQi CMS provides flexible template tags, allowing you to easily achieve these functions.### Understand the composition of visual elements on a single page In Anqi CMS, each single page can have exclusive visual elements to meet different display needs

2025-11-08

How to define temporary variables or use macro functions to organize complex display logic in templates?

When using Anqicms to manage website content, we often encounter scenarios where we need to display complex data or reuse similar layouts.If the display logic in the template is not organized effectively, it will soon become long and difficult to read, and it will also be particularly difficult to maintain.Luckyly, Anqi CMS's template engine (which supports Django template engine syntax) provides powerful tools such as defining temporary variables and using macro functions, which can help us elegantly solve these problems, making the template code clear and efficient.Why do we need more flexible template logic

2025-11-08

How does AnQiCMS generate structured data through Json-LD tags to optimize the display results of search engines?

In today's highly competitive online environment, it is more important than ever to make your website content stand out in search engines.Relying solely on keyword stuffing and traditional SEO methods is no longer enough to achieve **results.Structured data, especially structured data implemented through Json-LD format, is becoming a key factor in improving search engine display results and attracting more target users' attention.AnQiCMS (AnQiCMS) knows this and provides powerful and flexible features to help you easily master this technology.### Structured Data

2025-11-08

How to efficiently display multi-site content in Anqi CMS?

In today's complex digital environment, many enterprises and content creators no longer satisfy with single-site operations.Brand expansion, regional coverage, and product line segmentation often require multiple independent websites to carry different content and marketing strategies.How can one maintain the independence of content across various sites while also efficiently managing and displaying it uniformly, which is a challenge faced by many operators.AnQi CMS, with its specially designed ability for multi-site management, provides us with an elegant solution.###

2025-11-08

How to implement multi-language content switching and display in Anqi CMS?

AnQiCMS plays an important role in global content promotion, and its multilingual content switching and display features can help your website easily meet the needs of users in different languages.This not only expands your potential market, but also optimizes the browsing experience of users in different regions.In AnQiCMS, to implement the display of multilingual content, we first need to understand its core design concept: multilingual sites are usually regarded as independent "sites" for management.This means, if you need a Chinese version and an English version of a website, they are on AnQiCMS

2025-11-08