In the template world of AnQi CMS, data is not just raw text or numbers; they are the cornerstone of excellent website content.However, the original data often needs to be polished before it can present itself in a**proper manner to the user.This is where the template filter becomes an indispensable and powerful assistant to us.They are like the 'Swiss Army knife' of data processing, capable of performing various transformations, formatting, and refining template variables, making data shine with new brilliance and satisfying a variety of display needs.
As an experienced website operations expert, I am well aware of the importance of flexible data processing capabilities in enhancing user experience and optimizing content display.AnQiCMS is an enterprise-level content management system developed based on the Go programming language. Its template engine is not only powerful but also provides a rich set of built-in filters, allowing even non-programming-savvy operators to easily handle complex data transformation tasks.This article will delve into the commonly used filters supported by AnQiCMS, revealing how they cleverly handle template data, such as string truncation, date formatting, etc., to help you build high-quality website content more efficiently.
Filter Overview: Make data processing elegant
In the AnQiCMS templates, the way of using filters to process data is very intuitive and elegant. Usually, we would use{{obj|filter_name:param}}This is the syntax structure. Whereobjis the template variable you need to handlefilter_nameis the name of the filter, andparamThis is an optional parameter based on the filter function. This chained call design allows you to process the data in multiple steps at once.
Next, we will classify and introduce the commonly used filters of AnQiCMS.
I. Date and Time: Accurately present the 'tense' of the content
The display of time is ubiquitous in the website content, whether it is the publication time of articles, the deadline of events, or the listing time of products, it all needs to be presented in a specific format. AnQiCMS provides two powerful time processing filters for this purpose:
stampToDate(时间戳, "格式")This built-in function is specifically used to convert a 10-digit Unix timestamp (such as1609470335Convert it to a readable date and time string. Its strength lies in the fact that you can use the "format" parameter to precisely define the output year, month, day, hour, minute, second, even the day of the week, following the Go language's time formatting rules, for example"2006-01-02 15:04:05"It can output the standard year, month, day, hour, minute, and second. This is particularly useful when directly obtaining timestamps from a database.date:"格式"(or its alias)time): If your data source is already in Go languagetime.TimeAn object type, thendateThe filter is a **selection. It also supports Go language's time formatting strings, allowing you to display time information in the same flexible manner. It should be noted that,dateFilter cannot handle timestamps directly, this is the main difference withstampToDate.
By these filters, you can ensure that all time information on the website is presented in a user-friendly and unified format, enhancing professionalism.
【en】Two, string processing: Refine each section of text
The core of the website content is text, and the refined processing of text is the key to improving the reading experience. AnQiCMS provides a series of powerful string filters:
- Truncation and omission:
truncatechars:长度andtruncatewords:数量When the text is too long, we often need to truncate it and add an ellipsis (•••) to it....).truncatecharsTruncating by character count may cut off words; whereastruncatewordsThen it is cut by word count, usually maintaining the integrity of meaning.truncatechars_html:长度andtruncatewords_html:数量: For rich text content containing HTML tags, using the above filter directly may destroy the HTML structure._htmlSuffix filters can intelligently retain the integrity of HTML tags while truncating, ensuring that the page renders correctly.
- Case conversion:
upperandlowerConvert a string to uppercase or lowercase, suitable for uniform text style or data cleaning.capfirstConvert the first letter of a string to uppercase, commonly used for capitalizing the first letter of a sentence.titleConvert the first letter of each word in a string to uppercase, commonly used for title formatting.
- Character Removal and Replacement:
cut:"字符"Remove a specified single character from any position in a string.replace:"旧词,新词"Replace all 'old words' with 'new words', powerful, can be used for batch correction of text content.trim,trimLeft,trimRightRemove leading, trailing, or specified characters from both sides of a string, used for cleaning input data or formatting output.
- Padding and alignment:
center:长度/ljust:长度/rjust:长度[en] : Pad a string to a specified length and center, left-align, or right-align, with spaces filling the remainder. This is very useful for creating fixed-width text layouts or reports with specific formats.
- Line Break Handling:
linebreaksandlinebreaksbr: Converts line breaks in text to HTML's<p>or<br/>tags, making it easier to display multi-line text correctly on web pages.linenumbersAdd line numbers to each line of multi-line text, commonly used for code display or annotation of specific content.
- URL and link processing:
urlizeandurlizetrunc:长度Automatically identify URLs and email addresses in the text and convert them into clickable HTML links.urlizetruncIt can also truncate link text that is too long and add an ellipsis.urlencodeandiriencodeEncode URL parameters to ensure the validity and security of the URL, avoiding issues caused by special characters.
- Escape special characters:
escape(or its alias)e) andescapejsTranslate HTML or JavaScript code to escape special characters, preventing XSS (Cross-Site Scripting) and other security issues.AnQiCMS will automatically escape HTML output by default, but these filters provide more detailed control.addslashesAdd a backslash before predefined special characters (such as single quotes, double quotes, backslashes) to generate safe JS strings or database queries.safeThis is a special filter that tells the template engine that the processed content is 'safe' and does not require HTML escaping.This is very critical when displaying user-submitted rich text content (such as article text), but be sure to ensure the safety of the content source to prevent XSS vulnerabilities.
III. Numbers and Logic: The Tools for Data Operations and Conditional Judgments
In addition to text, numbers are also an important part of template data. AnQiCMS filters can also handle this easily:
- Mathematical Operations and Type Conversions:
add:值: Add numbers or strings together to perform simple mathematical operations or string concatenation.integerandfloatConvert a string to an integer or a floating-point number, which is convenient for numerical calculations.floatformat:位数Format a floating-point number to retain a specified number of decimal places.divisibleby:除数Determine whether a number can be evenly divided by another number, returning a boolean value, often used in loops to control the style of even or odd rows.
- Length and count:
length:Get the length of a string, array, or map (number of elements).length_is:长度:Check if the length of a variable is equal to a specified value, returns a boolean value.wordcount:Count the number of words in a string.count:关键词Calculate the number of times a keyword appears in a string or array.
- Default value setting:
default:"默认值"anddefault_if_none:"默认值"When the variable is empty ornildisplay a preset default value to avoid blank pages or errors.
- Conditional judgment assistant:
yesno:"yes,no,maybe"Returns the corresponding string according to the boolean value of the variable (true, false, empty) for more friendly text prompts.
- Get a specific number:
get_digit:位置Extract the number at a specified position (from the end) from the number, commonly used for handling IDs or serial numbers.
Four, array/list processing: Display a set of data in an orderly manner.
When dealing with collection type data (such as article lists, tag lists), filters can help us better organize and display:
- Splitting and拼接:
split:"分隔符"Split a string into an array of strings using a specified delimiter.make_listSplit each character of a string into an array element.fieldsSplit a string into an array of words using spaces.join:"拼接符"Join array elements into a string with a specified separator.
- Slice elements:
slice:"from:to": Slice elements from a specified range in an array or string.
- Random selection:
randomSelect a random element or character from an array or string.
thumb: Get the thumbnail of an image based on its address.
V. Debugging and Assistance: Enhance development efficiency.
dumpIn the process of template development, understanding the structure and value of variables is crucial.dumpFilters can completely print out the structure type and value of any variable, greatly assisting in debugging.stringformat:"格式定义"This is a very general formatting tool, similar to the Go language'sfmt.SprintfIt can format and output numbers, strings, and other arbitrary values according to the C language style format string.repeat:次数Repeat a string a specified number of times, commonly used to generate test data or special visual effects.renderRender Markdown content into HTML for easy display of articles written in Markdown on the front end.
Summary
The template filters of AnQi CMS provide powerful and flexible tools for the dynamic display and fine management of website content.These filters can help you transform the raw data passed from the backend into elegant content that is easy for users to understand and appreciate, whether it is simple date formatting, complex string slicing, or the organization of collection data.Mastering them will greatly enhance your content operation efficiency and website user experience, making your website stand out among numerous content platforms.
Common Questions (FAQ)
1.stampToDateanddateWhat are the main differences between the filters?
stampToDateThe filter is specifically used to process Unix timestamps (usually 10-digit integers), converting them to a readable date and time format.dateThe filter expects an input in Go language.time.TimeAn object type, then format it. In short, if you get a timestamp from a database or other API,stampToDateIf your data is already of the Go language's native time type, thendateis more suitable. Both use the Go language's time formatting string as an argument.
2. How to safely display user submitted content with HTML tags in AnQiCMS templates?
When the content submitted by the user (such as the article body) may contain HTML tags, by default, the AnQiCMS template engine will escape them to prevent cross-site scripting attacks (XSS). If you want these HTML tags to be parsed and displayed normally by the browser instead of displaying them as raw code, you can usesafea filter. For example{{ archive.Content|safe }}But, usingsafeFilter means you trust the source of the content is safe and does not contain malicious code. Therefore, it is the crucial first step to strictly sanitize and validate the content submitted by users on the backend, and then use it in the template.safeFilter.
3.truncatecharsandtruncatechars_htmlWhat are the main application scenarios?
truncatecharsThe filter is used to truncate plain text strings to a specified character length and add an ellipsis.It may truncate words when cutting, suitable for scenarios with strict text length limits and plain text content, such as article summaries or list titles.