In the template world of AnQi CMS, data is not just raw text or numbers, they are the foundation of the content of a great website.However, the original data often needs to be polished before it can be presented to the user in a** posture.At this point, the template filter has become an indispensable helper for us.They are like the 'Swiss Army knife' of data processing, capable of performing various transformations, formatting, and refining template variables, making the data shine with new brilliance and meeting all kinds 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 language, its template engine is not only powerful but also provides a rich set of built-in filters, allowing even less skilled 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 template, the way filters are used to process data is very intuitive and elegant. Usually, we would use{{obj|filter_name:param}}This is the syntax structure. AmongobjIt is the template variable you need to handle,filter_nameAnd it is the name of the filter, whileparamThis is an optional parameter based on the filter function. This chained call design allows you to process data multiple times at once.

Next, we will classify and introduce the commonly used filters of AnQiCMS.

1. Date and time: Accurately present the 'tense' of the content.

The display of time is ubiquitous on website content, whether it is the publication time of articles, the deadline of events, or the product launch time, it needs to be presented in a specific format. AnQiCMS provides two powerful time processing filters for this:

  • stampToDate(时间戳, "格式")This built-in function is specifically used to convert a 10-digit Unix timestamp such as1609470335Convert to a readable date-time string. Its strength lies in the ability to use the "format" parameter to precisely define the output of the year, month, day, hour, minute, second, even the week, 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 language,time.TimeThe type of object, thendateThe filter is a **selection. It also supports Go language's time formatting strings, allowing you to display time information in a flexible manner. It should be noted that,dateThe filter cannot handle timestamps directly, which is one of the main differences with itstampToDatethe main difference.

Through these filters, you can ensure that all time information on the website is presented in a user-friendly and unified format, enhancing professionalism.

Chapter 2: String Processing: Refine Every Text Segment

The core of 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 text is too long, we often need to truncate and add an ellipsis (...)truncatecharsTruncating by character count may cut off words; whereastruncatewordsIt cuts according to the number of words, usually maintaining the integrity of meaning.
    • truncatechars_html:长度andtruncatewords_html:数量: Directly using the above filter for rich text content containing HTML tags may destroy the HTML structure._htmlThe suffix filter can intelligently retain the integrity of HTML tags while extracting, ensuring that the page renders correctly.
  • Case conversion:
    • upperandlowerConvert a string to uppercase or lowercase, suitable for unifying text styles or data cleaning.
    • capfirstConverts the first letter of a string to uppercase, commonly used for capitalizing the first letter of a sentence.
    • titleCapitalize the first letter of each word in a string, 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 for batch correction of text content.
    • trim,trimLeft,trimRightRemove leading and trailing, or both sides, of whitespace characters or specified characters, used to clean input data or format output.
  • Padding and alignment:
    • center:长度/ljust:长度/rjust:长度Center-align, left-align, or right-align a string to a specified length, filling the unused part with spaces. This is very useful for creating monospaced text layouts or specific formatted reports.
  • Line break processing:
    • linebreaksandlinebreaksbrTranslate line breaks to HTML in text<p>tags or<br/>Tag, convenient for correctly displaying multiline text on web pages.
    • linenumbers: Adds line numbers to each line of multiline text, commonly used for code display or annotation of specific content.
  • URL and Link Handling:
    • urlizeandurlizetrunc:长度: Automatically identify URLs and email addresses in text and convert them into clickable HTML links.urlizetruncYou can truncate the link text when it 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) orescapejsEscape special characters in HTML or JavaScript code to prevent XSS (cross-site scripting) and other security issues.AnQiCMS defaults to automatically escaping HTML output, but these filters provide more fine-grained control.
    • addslashesAdd a backslash before predefined special characters (such as single quotes, double quotes, backslashes), often used 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 the rich text content submitted by users (such as article content), but it is necessary to ensure the safety of the content source to prevent XSS vulnerabilities.

The, Number and Logic: The Tool of Data Calculation and Conditional Judgment

In addition to text, numbers are also an important part of template data. The AnQiCMS filter can also easily handle:

  • Mathematical operations and type conversion:
    • add:值: Add or concatenate numbers or strings to perform simple mathematical operations or string concatenation.
    • integerandfloatConvert a string to an integer or floating-point number for easy numerical calculation.
    • floatformat:位数Format a floating-point number to retain a specified number of decimal places.
    • divisibleby:除数: Determines if a number can be evenly divided by another number, returns a boolean value, often used for style control of even or odd rows in loops.
  • Length and count:
    • length: Get the length of a string, array, or map (number of elements).
    • length_is:长度: Determine if the length of a variable is equal to a specified value, returning a boolean value.
    • wordcount: Count the number of words in a string.
    • count:关键词Calculate the number of times a specific keyword appears in a string or array.
  • Default value setting:
    • default:"默认值"anddefault_if_none:"默认值"When a variable is empty ornildisplay a preset default value to avoid blank pages or errors.
  • Conditional Judgment Aid:
    • yesno:"yes,no,maybe"Returns the corresponding string based on the boolean value (true, false, empty) of the variable, for more friendly text prompts.
  • Get a specific number:
    • get_digit:位置Get the number at a specified position (from the end) in the number, often used to handle IDs or serial numbers.

4. Array/List Processing: Display collection data in order.

When dealing with collection types of data (such as article lists, tag lists), filters can help us better organize and display:

  • Split and concatenate:
    • split:"分隔符"Split a string into an array of strings by a specified delimiter.
    • make_listSplit each character of a string into array elements.
    • fieldsSplit a string into an array of words by spaces.
    • join:"拼接符"Join array elements with a specified separator to form a string.
  • Cut elements:
    • slice:"from:to": Cut elements from an array or string within a specified range.
  • Random selection:
    • random: Select a random element or character from an array or string.
  • thumb: Retrieve the thumbnail of an image based on its address.

Five: Debugging and Assistance: Improving Development Efficiency

  • dumpIt is crucial to understand the structure and value of variables during template development.dumpFilters can completely print the structure and value of any variable, greatly assisting in debugging.
  • stringformat:"格式定义"This is a very general formatting tool, similar to the Go language.fmt.SprintfIt can format numbers, strings, and other arbitrary values according to the C language style string format.
  • repeat:次数:Repeat a string a specified number of times, often used to generate test data or special visual effects.
  • renderTranslate Markdown content to HTML for easy display of Markdown-written articles on the front end.

Summary

The template filter of Anqi CMS provides a powerful and flexible tool for dynamic display and fine management of website content.Whether it is simple date formatting, complex string truncation, or the organization of collection data, these filters can help you convert the original data passed from the backend into elegant content that is easy for users to understand and appreciate.Mastering them will greatly enhance your content operation efficiency and website user experience, making your website stand out among many content platforms.


Frequently Asked Questions (FAQ)

1.stampToDateanddateWhat are the main differences of the filter?

stampToDateA filter is specifically used to process Unix timestamps (usually a 10-digit integer), converting them to a readable date and time format. AnddateThe filter expects to input a Go languagetime.TimeType an object and then format it. In short, if you get a timestamp from a database or other API, please usestampToDateIf your data is already a native Go language time type, thendateis more suitable. Both use the Go language time formatting string as a parameter.

How to safely display user submitted content containing HTML tags in AnQiCMS templates?

When the user submits content (such as article text) that 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 by the browser instead of being displayed as raw code, you can usesafethe filter. For example{{ archive.Content|safe }}But, usesafeThe filter means you trust the source of the content is safe, it 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 is the main application scenario?

truncatecharsThe filter is used to truncate plain text strings to a specified character length and add an ellipsis.It may truncate words when slicing, suitable for scenarios with strict text length limits and pure text content, such as article summaries or list titles. And