As an experienced website operations expert, I know the importance of content presentation and processing efficiency in daily work.AnQiCMS (AnQiCMS) provides us with many conveniences in content management with its flexible and efficient features.Filter chaining callIt is also a powerful tool for us to achieve refined content presentation and efficient template development.
Today, let's delve into the advanced usage techniques of the AnQi CMS filter chaining, and how to巧妙ly integrate these technologies into daily operations to make our website content more vivid and precise.
Unlock the potential of the AnQi CMS template: Advanced techniques of chaining filter calls in depth analysis
In the template design of AnQi CMS, filters play a crucial role.It allows us to modify, format, or process variable data directly at the template level without changing the backend logic.Filter chaining callIt emerged as a result of necessity, acting like a data pipeline, taking the output of one filter as the input for the next, progressing layer by layer, until it finally presents the effect we desire.
What is the chain call of filter? Why is it so powerful?
In simple terms, the chain call of filter is through|The symbol links multiple filters together for continuous processing of the same data.For example, we may need to truncate a descriptive text first, then remove the HTML tags, and finally convert it to lowercase.{{ 文章描述 | truncatechars:50 | striptags | lower }}.
The powerful aspect of this ability is:
- High flexibility and efficiency:The page display logic is closely integrated with the front-end requirements, no frequent modification of the back-end code is needed, which greatly accelerates the iteration speed.
- Simplicity and readability of the code:The complex conversion logic is encapsulated in a concise filter chain, making the template code easier to understand and maintain.
- Refined presentation of data:Ensured that the website content is displayed in the most suitable and aesthetically pleasing format across different scenarios, whether it be SEO meta descriptions, list summaries, or user comments.
- Reduced development and maintenance costs:Reduced the communication cost between frontend engineers and backend engineers, improving the overall collaboration efficiency of the team.
Master the advanced techniques of filter chaining, which allows us to operate and develop templates with ease on the website.Next, I will combine actual operation scenarios to reveal these practical skills.
I. Refine content presentation: Balance beauty and SEO
The display of website content should not only attract users but also meet the requirements of search engine optimization (SEO). The chaining call of the filter provides strong support in this aspect.
Highly efficient truncation and formatting of summaries:On the list page or search results, we usually need to display a brief summary of the article. To avoid content being too long and affecting the layout, remove potential HTML tags interference, and ensure the number of characters meets SEO requirements, we can operate in this way:
{{ item.Description | truncatechars_html:120 | safe }}This chain first usestruncatechars_html:120To truncate the description containing HTML tags and intelligently maintain the integrity of the HTML structure, while limiting the number of characters to 120 (including ellipsis).safeThe filter ensures that HTML tags are parsed correctly instead of being displayed as escaped.- If the description does not contain HTML or if all formatting needs to be completely removed, you can use
striptags:{{ item.Description | striptags | truncatechars:150 }}This will first remove all HTML tags, and then truncate the plain text content.
Unify the case of titles and keywords:To maintain brand consistency or comply with certain specific SEO standards, we may need to unify the case of titles or keywords.
{{ item.Title | title }}:titleThe filter will capitalize the first letter of each word and the rest in lowercase, which is very suitable for displaying article titles.{{ item.Keywords | lower | replace:", ","-" }}This example can convert all keywords to lowercase and replace commas and spaces between multiple keywords with hyphens-This is very useful when generating URL-friendly keyword tags.
URL processing and encoding: Ensure the validity and security of the link.In certain scenarios, we need to dynamically generate URL parameters with special characters in templates, or convert plain text URLs into clickable links.
{{ "你的查询词" | urlencode }}:urlencodeThe filter will encode special characters in the string to ensure that they do not cause errors when used as URL parameters.{{ 文章内容 | urlize | safe }}:urlizeThe filter will automatically identify URLs or email addresses in the text and convert them into clickable items<a>Tags will be added automaticallyrel="nofollow"Properties, which is very convenient for handling user submitted content. If you want to limit the display length, it can also be combined withurlizetrunc:30Use.
Part two: Data cleaning and format conversion: Making data more 'obedient'
The data format sent from the backend may not always directly meet the needs of front-end display. By using a chain of filters, we can efficiently clean and transform the data.
Strip and Replace: Clean Data Content
{{ item.Content | striptags | removetags:"script,iframe" | safe }}This chain first removes all HTML tags, then specifically removesscriptandiframetags, and finally usessafeEnsure that the remaining HTML content is parsed, which is particularly critical for handling external collection or user-submitted content that requires high security.{{ item.Content | replace:"旧词,新词" | replace:"另一个旧词,另一个新词" | safe }}By using continuouslyreplaceFilter, which can achieve batch replacement of multiple keywords, such as unified sensitive words, brand name modification, etc. This is very efficient in content updates or brand strategy adjustments.
Type Conversion and Default Values: Enhancing Data ToleranceSometimes, we may receive numbers in string format from the backend, or a field may be empty.
{{ item.Price | float | stringformat:"%.2f" }}Ifitem.Priceis a string,floatIt will convert it to a floating-point number, thenstringformat:"%.2f"It will format it as a string with two decimal places. This is very practical in scenarios such as e-commerce product price display.{{ item.Author | default:"匿名用户" | upper }}Ifitem.AuthorThe content is empty, then display 'Anonymous User', otherwise display the author's name, and then convert it to uppercase uniformly. This ensures the integrity of the key information on the page and avoids display problems caused by empty values.
Text structuring and reorganization: flexible handling of lists and stringsWhen data comes as a comma-separated string while we need to treat it as a list, or vice versa.
{% set tags_array = item.Tags | split:", " %}{% for tag in tags_array %}{{ tag | upper }} {% endfor %}Here, we first willitem.TagsThroughsplit:", "Filter the string into an array of strings, then iterate over the array, convert each tag to uppercase and display it.{{ some_list | join:" | " }}: Conversely, if there is a list of stringssome_listThroughjoin:" | "We can elegantly concatenate it into a string separated by vertical bars.
III. Dynamic conditional judgment and content generation: Enhancing template intelligence
Filter chain calls are not limited to simple formatting, they can also be combined with conditional judgment tags to realize more intelligent template logic.
Content presented conditionally:
{% if item.Content | contain:"图片" %}<p>本文包含图片</p>{% endif %}: combinedcontainFilter, we can detect specific keywords in the content to dynamically display hints.{% if user.Status | yesno:"VIP,普通用户,未知" == "VIP" %}欢迎尊贵的VIP用户!{% endif %}:yesnoThe filter can return custom three states based on boolean or null values, combined with conditional judgment, to achieve dynamic welcome messages for user levels.Layout and text effects:
{{ "重要提示" | repeat:3 | upper }}Translate the content of 'auto' to 'English' and keep the original format of the JSON array.{{ item.Title | center:40 }}English: Center the title text within 40 characters, which is very helpful for specific layout requirements (such as console information output).
English: Practical tips and **practice
- English: **Understanding