In the content operation of AnQiCMS, we often encounter the need to dynamically process strings displayed on the front end of the website.Whether it is to improve the user reading experience, optimize the search engine inclusion, or maintain the consistency of content display, flexibly concatenating or replacing strings is a very practical skill.The Anqi CMS provides powerful and convenient tools for us with its efficient template engine based on the Go language, allowing these operations to be easily implemented at the template level.
String concatenation: let information flow smoothly
When combining multiple variables or fixed text to form a complete sentence, string concatenation becomes particularly important.This is very common in scenarios such as building dynamic titles, breadcrumb navigation, product descriptions, or any other situation where combined display of information is needed.
In AnQiCMS templates, the most intuitive way to concatenate is to combine variables with text content.The template will intelligently connect them together.
{{ archive.Title }} - {{ archive.Category.Title }}
This will generate content similar to 'AnQiCMS Template Tips - Template Development'. Similarly, you can also concatenate fixed text:
{{ item.Title }}到{{ combine.Title }}的旅游线路
When we need to perform more complex concatenation, especially involving the mixing of numbers and strings, or when we need clearer type handling,addThe filter comes into play.addFilter can intelligently add two values, whether it is adding numbers or concatenating strings.If one of the values cannot be recognized as a number for arithmetic operations, it will attempt to perform string concatenation.
For example, display a product's price and add the currency unit afterwards:
{{ item.Price|add:" 元" }}
If your data itself is a list (array), and you want to concatenate all the elements into a string,joinFilter is your reliable assistant. For example, an article may have multiple tags, and you want them displayed in the form of a comma-separated list:
{{ item.Tags|join:", " }}
This way you can["SEO", "优化", "内容"]displayed asSEO, 优化, 内容.
String Replacement and Formatting: Master Display Content
Content replacement, as the name implies, is to replace a specific part of the string with the new content we want.This is very useful for unifying brand terms, correcting error messages, or hiding or displaying sensitive words in specific scenarios.
AnQiCMS templates providereplaceFilter, it is the main tool for string replacement. You need to specify the old keyword and the new keyword, separated by a comma.
For example, replace 'AnQiCMS' in the article description with 'AnQiCMS':
{{ item.Description|replace:"安企CMS,AnQiCMS" }}
If you only want to remove the parts of the string that you don't need, such as extra spaces or certain characters,cutandtrimthe filter can make a big difference.cutThe filter will remove all specified characters from the string.
For example, remove all spaces from the string:
{{ "Hello World"|cut:" " }} {# 输出:HelloWorld #}
whiletrimThe filter removes whitespace characters from the beginning and end of a string. If you need more fine-grained control, you can also usetrimLeft(remove the beginning) andtrimRight(remove the end).
For example, remove leading and trailing spaces from a string:
{{ " Hello World "|trim }} {# 输出:Hello World #}
Besides direct replacement operations, AnQiCMS also provides various formatting filters that change the display form of strings and achieve a certain sense of "replacement":
Extract text:
truncatecharsandtruncatewordsThe filter can help you truncate overly long text and automatically add an ellipsis at the end.The former is cut by character count, and the latter is cut by word count.truncatechars_htmlortruncatewords_htmlExtract safely to avoid destroying HTML structure.{{ item.Content|truncatechars:100 }} {# 截取前100个字符 #}Case conversion:
upper/lower/capfirst(Capitalize first letter) andtitleCan easily adjust the case format of text to meet page design or SEO standards.{{ item.Title|upper }} {# 全部大写 #}Time formatting:
stampToDateThe filter can format timestamps into the date or time format we need, which is very practical in scenarios such as displaying publication dates, update times, etc.{{ stampToDate(item.CreatedTime, "2006年01月02日 15:04") }}URL processing:
urlizeandurlizetruncThe filter can automatically identify URLs in text and convert them into clickable hyperlinks, and you can also choose to truncate the link text.urlencodeIt is used for escaping URL parameters.HTML tag processing:
striptagsCan remove all HTML tags,removetagsThese can be used to remove specified HTML tags. They are very useful when displaying plain text summaries or cleaning up user input.
It is especially important to note that if the content you concatenate or replace contains HTML tags, and you want the browser to correctly parse these tags instead of displaying them as plain text, then you must remember to usesafeFilter. This is the default behavior of AnQiCMS template engine for security considerations (to prevent XSS attacks).
{{ articleContent|safe }} {# 确保HTML内容被正确解析 #}
Why are these operations important?
Flexibly using string concatenation and replacement techniques can not only make the presentation of website content more rich and dynamic, but also bring many benefits:
- Enhance user experience:Generate more attractive titles and summaries dynamically, making the page content more readable and relevant.
- Optimize SEO:Dynamically adjust the page according to the context of the page
<title>/<meta description>Generate URLs that are more in line with search engine crawling rules to improve the ranking of the website in search results. - Improve operational efficiency:Reduce repetitive backend editing work, define content display rules once through templates, and no manual modification of the front-end display is needed when updating content.
Master these string manipulation techniques at the template level, undoubtedly will greatly enhance our efficiency and flexibility in using AnQiCMS for website content operation.
Common Questions (FAQ)
1. What is the difference between the "Full Site Content Replacement" function of AnQiCMS backend and string replacement in templates?
The “Full Station Content Replacement” feature (such as “Document Keyword Replacement”) on the back endat the database levelModify the actual content of the website in bulk. Once replaced, the original content is permanently changed. The string concatenation and replacement operations in the template are only performed whendisplayed to the front endPerform dynamic processing without modifying the original content in the database.These two methods have different focuses, background replacement is suitable for large-scale content correction, and template operation is used for flexible adjustment of the display layer.
2. Why does the front-end display the original code instead of the rendered style after I concatenate or replace some content containing HTML tags in the template?
This is the default mechanism adopted by AnQiCMS template engine for website security (to prevent cross-site scripting XSS attacks), which automatically escapes the output HTML content,<Converted to<If you are sure.