As a senior security CMS website operator, I fully understand the importance of content in attracting and retaining users.A powerful and flexible template system that allows us to present content accurately according to different scenarios and user needs.AnQiCMS relies on its Django template engine syntax to provide us with rich string processing capabilities, whether it is to extract, replace, or format, it can be easily achieved, thereby transforming raw data into engaging page content.
Retrieving and basic processing of string variables in AnQiCMS template
In AnQiCMS templates, we usually use double curly braces{{ 变量名 }}Output variable content. These variables may come from document titles, content descriptions, category names, system settings, etc.However, the original string data often needs to be modified to be presented better on the front-end page.For example, an abstract of a long article may need to be truncated to fit a card layout, specific words in a description may need to be replaced to maintain brand consistency, or a timestamp may need to be formatted into a readable date.AnQiCMS template engine is built-in with a powerful Filters mechanism, allowing us to use the pipe character|Pass the data to one or more filters for processing.
Flexible string truncation strategy
In many content display scenarios, we all need to truncate overly long strings to maintain a tidy and unified layout of the page.AnQiCMS provides various cutting methods, which can meet the needs of character, word, and even HTML safe cutting.
When we want to truncate strings by character count, we can usetruncatecharsFilter. For example,{{ item.Description|truncatechars:90 }}Willitem.DescriptionTruncate to a maximum of 90 characters and add an ellipsis (…). If you need to truncate by word count, you can usetruncatewordsThis is more natural for languages that use words as units (such as English), for example{{ item.Description|truncatewords:20 }}The first 20 words will be retained.
It should be noted that if the extracted content contains HTML tags, use it directlytruncatecharsortruncatewordsIt may destroy the HTML structure, causing the page to display abnormally. In this case, we should choosetruncatechars_htmlandtruncatewords_htmlFilters. These intelligent filters can identify and retain the integrity of HTML tags, ensuring that the extracted content is still a valid HTML fragment.
Other than based on character or word truncation,sliceThe filter also provides a more refined slicing operation. It can be used to extract a specified range of strings, similar to array slicing in programming languages. For example,{{ "HelloWorld"|slice:"0:5" }}It will output 'Hello'. This is very useful when dealing with strings that have a fixed format or need to extract specific position information.
String content replacement and correction
In addition to truncation, replacing and correcting string content is also a common requirement in template operations. AnQiCMS's filter mechanism makes these operations intuitive and efficient.
cutThe filter can remove all specified characters or substrings from a string. For example,{{ "Hello World"|cut:" " }}You can remove all spaces from a string and output "HelloWorld". This is very convenient for cleaning data or removing unnecessary punctuation.
When processing text, we may need to adjust its case format.upperThe filter can convert all characters to uppercase,lowerwhile the filter converts to lowercase,capfirstThe filter only converts the first letter of the string to uppercase.titleThe filter goes further, it capitalizes the first letter of each word in a string and converts the rest to lowercase, which is very suitable for title formatting.
For articles containing external links, we sometimes need to perform special processing, such as automatically addingrel="nofollow"attributes or converting plain text URLs into clickable links.urlizeThe filter can automatically detect URLs and email addresses in text and convert them into HTML with appropriate links<a>Label. If you need to limit the display length of the link,urlizetruncThe filter can truncate the long URL text while converting it to a link.
When it comes to cleaning HTML tags for user submitted content, it is a critical step to prevent cross-site scripting attacks (XSS).striptagsThe filter can remove all HTML and XML tags from a string, leaving only plain text content. If you need to retain some tags while removing others,removetagsThe filter can specify the list of HTML tags to be removed.
Furthermore,linebreaksandlinebreaksbrThe filter can convert newline characters in text to HTML's.<p>tags or<br>Label, ensure that multiline text is displayed correctly on the page as a paragraph or forced line break.
Refined formatting of string content.
In addition to truncation and replacement, presenting string data in a specific format is the core of template processing. AnQiCMS provides a rich set of formatting tools.
Timestamp is a common date storage method in databases, but users usually need to see easily readable date and time formats.stampToDateIs an AnQiCMS provided very practical tag, which can directly format 10-digit timestamps into the date and time string we need. It accepts timestamps and Go language time format strings as parameters, for example{{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}You can format the timestamp in the form of “Year-Month-Day Hour:Minute”.
For numeric string types,floatformatThe filter can be used to control the display accuracy and the number of decimal places for floating-point numbers. For example,{{ 34.23234|floatformat:2 }}the output will be "34.23".
When we need to concatenate multiple strings or array elements into a single string,joina filter is very useful. It can specify a delimiter to concatenate all elements in the array, such as{{ intList|join:", " }}. On the contrary,splitThe filter can split a string into an array of strings according to the specified delimiter.
stringformatThe filter provides similar functionality to the Go languagefmt.Sprintf()The function allows us to perform complex formatting of variables based on the format string, for example{{ 0.55555|stringformat:"%.2f" }}.
Safe output and escaping control
In AnQiCMS templates, security is considered by default.To prevent XSS attacks, the template engine defaults to HTML-encoding all output variables.This means that HTML tags and special characters will be converted to entity encoding, for example<Will become<.
However, in some cases, we may need to output strings containing HTML content (such as the body of an article, which has been edited through a rich text editor). At this point, we can usesafeA filter is used to explicitly inform the template engine that the string is "safe" and does not require escaping, for example{{ articleContent|safe }}.
withsafeCorrespondingly,escapeThe filter can force HTML escaping. It is rarely necessary to use it explicitly when default automatic escaping is enabledescape, but inautoescape offEnsure that a variable is escaped in the block when it comes in handy.autoescapeThe tag allows us to locally control whether to enable automatic escaping, for example.{% autoescape off %} ... {% endautoescape %}The content inside the block will not be automatically escaped.
By flexibly using these filters and tags, AnQiCMS website operators can finely control the display method of content, not only improving the user experience, but also enhancing the professionalism and security of the website.
Frequently Asked Questions (FAQ)
1. Why did I use a string filtertruncatecharsbut the HTML structure on the page was destroyed?
This is usually because your content contains HTML tags.truncatecharsThe filter is based on the count of plain text characters; it does not understand the semantics of HTML tags.When extracting in the middle of a tag, it will cause the tag to be incomplete. To safely extract content containing HTML, you should usetruncatechars_htmlortruncatewords_htmlFilters that intelligently maintain the integrity of the HTML structure when extracting.
2. I want to automatically turn all the phone numbers in the article content into clickable links, does AnQiCMS template have this feature?
AnQiCMS template does not have a built-in filter to directly recognize and convert phone numbers into links.urlizeThe filter is mainly used for standard URLs and email addresses.If you need to implement automatic phone number linking, you may need to use JavaScript on the front-end, or pre-complete this kind of replacement when processing content on the back-end.For batch replacement of content in the background, the "Whole Site Content Replacement" function of AnQiCMS may be a more suitable tool, but that is done before the content is stored or published, rather than dynamic processing at the template level.
3. How to format a date timestamp in a template to different display styles, such as showing only the year or only the hour and minute?
You can usestampToDateThe tag is used to achieve this. The tag accepts a 10-digit Unix timestamp and a Go language time format string as parameters.The date formatting in Go language is based on a fixed reference time2006-01-02 15:04:05.
- To display only the year, you can use
{{ stampToDate(item.CreatedTime, "2006") }}. - You can only display hours and minutes using
{{ stampToDate(item.CreatedTime, "15:04") }}. By adjusting the format string, you can generate various date and time display formats as needed.