As an experienced CMS website operation personnel in the field of information security, I am well aware of the importance of content in attracting and retaining users.An extremely powerful and flexible template system that allows us to accurately present content according to different scenarios and user needs.AnQiCMS with its Django template engine syntax, provides us with rich string processing capabilities, whether it's for slicing, replacing, or formatting, it can be easily achieved, thus transforming raw data into engaging page content.
AnQiCMS template string variable acquisition and basic processing
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 better present on the front-end page.For example, an abstract of a long article may need to be truncated to fit the card layout, specific words in a description may need to be replaced to maintain brand consistency, or timestamps may need to be formatted into readable dates.|Pass the data to one or more filters for processing.
Flexible string truncation strategy
In many content display scenarios, we need to truncate long strings to maintain the neat and unified layout of the page.AnQiCMS provides various ways of truncation to meet the needs of character, word, and even HTML secure truncation.
When we want to truncate strings by character count, we can usetruncatecharsa filter. For example,{{ item.Description|truncatechars:90 }}It willitem.DescriptionTruncate to the longest 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 especially noted that if the content to be truncated contains HTML tags, it should be used directlytruncatecharsortruncatewordsMay cause HTML structure to be destroyed, resulting in abnormal display of the page. At this time, we should choosetruncatechars_htmlandtruncatewords_htmlFilter. These smart filters can identify and retain the integrity of HTML tags, ensuring that the content extracted is still a valid HTML fragment.
Except for the extraction based on characters or words,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" }}The output will be 'Hello'. This is very useful when dealing with strings that have a fixed format or require extracting specific position information.
Replacement and correction of string content
The extraction, replacement, and correction of string content are also common requirements in template operations. AnQiCMS's filtering mechanism makes these operations intuitive and efficient.
cutThe filter can remove all specified characters or substrings from a string. For example,{{ "Hello World"|cut:" " }}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,capfirstFilter converts the first letter of a string to uppercase.titleFilter then goes a step further, converting the first letter of each word in a string to uppercase and the rest to lowercase, which is very suitable for formatting titles.
For articles containing external links, we sometimes need to perform special processing, such as automatically addingrel="nofollow"properties or converting plain text URLs to clickable links.urlizeThe filter can automatically detect URLs and email addresses in text and convert them to HTML with appropriate links<a>Label. If you need to limit the display length of the link,urlizetruncThe filter can truncate the URL text if it is too long while converting it to a link.
When it comes to user-submitted content, cleaning HTML tags 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.
In addition,linebreaksandlinebreaksbrThe filter can convert newline characters in text to HTML.<p>or<br>Label, ensure that multi-line text is displayed correctly on the page as a paragraph or forced line break.
Refined formatting of string content.
除了截取和替换,将字符串数据按照特定格式呈现是模板处理的核心。EnglishQiCMS 提供了丰富的格式化工具。
Timestamp is a common date storage method in databases, but users usually need to see a readable date and time format.stampToDateis a very practical tag provided by AnQiCMS, which can directly format a 10-digit timestamp into the date and time string we need. It accepts timestamp and Go language time format string as parameters, for example{{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}The timestamp can be formatted into the form of “Year-Month-Day Hour:Minute”.
For string representations of numbers,floatformatThe filter can be used to control the display precision and the number of decimal places of 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,joinfilters are very useful. They can specify a separator to concatenate all elements in the array, such as{{ intList|join:", " }}。Instead,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" }}.
Control of safe output and escaping
In AnQiCMS template, security is considered by default.To prevent XSS attacks, the template engine defaults to escaping all output variables.<Will become<.
However, in some cases, we may need to output strings containing HTML content (such as the main text of an article, which has been edited through a rich text editor). At this time, we can usesafeFilter to explicitly inform the template engine that this string is 'safe' and does not require escaping, for example{{ articleContent|safe }}.
WithsafeCorrespondingly,escapeThe filter can enforce HTML escaping. Although it is rarely needed to use explicitly when the default automatic escaping is enabledescape, but inautoescape offIt comes in handy when you need to ensure that a variable is escaped within a block.autoescapeThe tag allows us to locally control whether auto-escaping is enabled, for example{% autoescape off %} ... {% endautoescape %}The content within the block will not be auto-escaped.
By flexibly using these filters and tags, the website operators of AnQiCMS can finely control the way content is displayed, which not only improves the user experience but also enhances the professionalism and security of the website.
Common Questions and Answers (FAQ)
1. Why did I use a string filter, but the HTML structure on the page was destroyed?truncatecharsThis is usually because your content contains HTML tags.
This is usually because your content contains HTML tags.truncatecharsThe filter is based on pure text character counting, it does not understand the semantics of HTML tags.When truncating in the middle of a tag, it will cause the tag to be incomplete.truncatechars_htmlortruncatewords_htmlFilters that intelligently maintain the integrity of the HTML structure during extraction.
2. I want to automatically turn all phone numbers in the article content into clickable links, does AnQiCMS template have this feature?
AnQiCMS template itself does not have a built-in filter to directly recognize and convert phone numbers to links.urlizeThe filter is mainly used for standard URLs and email addresses.If you need to implement automatic linking of phone numbers, you may need to process it with JavaScript on the front-end, or pre-complete such replacements when handling content on the back-end.For batch replacement of content on the backend, AnQiCMS's 'Full Site Content Replacement' feature may be a more suitable tool, but it is performed before or when the content is stored or published, rather than dynamic processing at the template level.
3. How to format a date timestamp into different display styles in a template, such as only showing the year or only showing the hour and minute?
You can usestampToDateTo achieve this through tags.This tag accepts a 10-digit Unix timestamp and a Go language time format string as an argument.2006-01-02 15:04:05.
- To only show the year,
{{ stampToDate(item.CreatedTime, "2006") }}. - To display only hours and minutes, you can use
{{ stampToDate(item.CreatedTime, "15:04") }}. By adjusting the format string, you can generate various required date and time display formats.