How to concatenate or replace strings before displaying them?

Calendar 👁️ 73

In AnQiCMS (AnQiCMS) content operations, we often encounter the need to dynamically process strings displayed on the front end of the website.In order to enhance the user reading experience, optimize search engine inclusion, or maintain consistency in content display, it is a very practical skill to flexibly concatenate or replace strings.AnQi CMS, with its efficient template engine based on the Go language, provides us with powerful and convenient tools, making these operations easily achievable at the template level.

String concatenation: Make information flow smoothly

When we need to combine multiple variables or fixed text to form a complete sentence, string concatenation becomes particularly important.This is very common in scenarios where dynamic titles, breadcrumb navigation, product descriptions, or any information that needs to be combined for display are required.

In AnQiCMS templates, the most intuitive way to concatenate is to combine variables with text content directly.The template will intelligently connect them together. For example, if you want to display an article's title and its category:

{{ 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 clearer type handling is required,addThe filter comes into play.addThe filter can intelligently add two values together, whether it is adding numbers or concatenating strings.If one of the values cannot be recognized as a number for calculation, it will try to concatenate strings.

For example, display the price of a product followed by the currency unit:

{{ item.Price|add:" 元" }}

If your data itself is a list (array), and you want to concatenate all its elements into a single string,joinThe filter is your helpful assistant. For example, an article may have multiple tags, and you want them to be displayed in the form of a comma-separated list:

{{ item.Tags|join:", " }}

This way, you can["SEO", "优化", "内容"]displayed asSEO, 优化, 内容.

String replacement and formatting: precise control over displayed 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 information, or hiding or displaying sensitive words in specific scenarios.

AnQiCMS template providedreplaceThe filter is the main tool for implementing 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 unnecessary parts of a string, such as extra spaces or certain characters, thencutandtrimFilters can really shine here.cutThe filter will remove all matched specified characters from the string.

For example, remove all spaces from a string:

{{ "Hello World"|cut:" " }}  {# 输出:HelloWorld #}

AndtrimThe filter focuses on removing 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 #}

In addition to direct replacement operations, AnQiCMS also provides various formatting filters that change the display of strings, thereby achieving a certain sense of 'replacement':

  • Extract text: truncatecharsandtruncatewordsThe filter can help you truncate long text and automatically add an ellipsis at the end.The former is truncated by character count, the latter by word count. If the content contains HTML tags, it can also be usedtruncatechars_htmlortruncatewords_htmlExtract safely, avoid breaking HTML structure.

    {{ item.Content|truncatechars:100 }}  {# 截取前100个字符 #}
    
  • Case conversion: upper/lower/capfirst(Capitalize the first letter) andtitle(Each word with its first letter capitalized can easily adjust the case of the 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 useful 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.urlencodeThis is used for escaping URL parameters.

  • HTML tag processing: striptagsRemove all HTML tags,removetagsIt can remove the specified HTML tags. These are very useful when displaying plain text summaries, or cleaning user input content.

It is especially worth noting that if the content you concatenate or replace contains HTML tags, and you want the browser to correctly parse these tags rather than displaying them as plain text, then you must remember to usesafeFilter. This is the default behavior of AnQiCMS template engine for security reasons (to prevent XSS attacks).

{{ articleContent|safe }} {# 确保HTML内容被正确解析 #}

Why are these operations important?

Skillfully using string concatenation and replacement techniques not only makes the presentation of web content more rich and dynamic, but also brings many benefits:

  • Improve user experience:Generate more attractive titles and descriptions to make the page content more readable and relevant.
  • Optimize SEO:Dynamically adjust the page based on the page context.<title>/<meta description>Generate a URL that is more compliant with search engine crawling rules, thereby improving the ranking of the website in search results.
  • Improve operational efficiency:Reduce repetitive background editing work, define the content display rules once through a template, and no manual modification of the front-end display is needed when the content is updated.

Mastering these template-level string manipulation skills will undoubtedly greatly enhance our efficiency and flexibility in operating website content with AnQiCMS.


Frequently Asked Questions (FAQ)

1. What is the difference between the "Full Site Content Replacement" function on the AnQiCMS backend and string replacement in templates?

The background "full site content replacement" function (such as "document keyword replacement") is located indatabase 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 on the contentdisplayed on the front end at that timePerform dynamic processing without modifying the original content in the database.Both of these methods have their own focus, background replacement is suitable for large-scale content correction, and template operation is used for flexible adjustment of the presentation layer.

2. Why is the original code displayed on the front end 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 will automatically escape the output HTML content, and<to&lt;Wait. If you are sure

Related articles

How to format floating-point numbers, controlling the number of decimal places displayed?

Website content operation, it is crucial to display numbers accurately, especially floating-point numbers such as prices and statistics, for enhancing user trust and page professionalism.AnQi CMS knows this, providing simple and flexible tools in its powerful template engine, allowing content creators to easily control the display format of floating-point numbers, including decimal places, without delving into complex programming.Next, we will discuss how to use built-in filters in Anqi CMS templates to elegantly format floating-point numbers.### Use `floatformat`

2025-11-08

How to truncate long text and display an ellipsis?

In website content presentation, we often need to refine some long text content, such as displaying abstracts on article list pages or showing brief descriptions on product cards.If the entire content is displayed directly, it may not only destroy the neat layout of the page, but may also affect the efficiency of users in quickly browsing information.Therefore, truncating long text and adding an ellipsis at the end has become a common strategy to improve user experience.AnQi CMS as an efficient content management system, built-in flexible template filters, can help us easily achieve this function

2025-11-08

How to safely display HTML or JS code in a template without escaping?

In AnQi CMS template development and content operations, sometimes we need to directly display HTML code or run JavaScript scripts on the page, rather than have them parsed by the browser as plain text.This usually occurs when it is necessary to embed third-party statistical code, advertisement scripts, or when displaying code examples in article content.However, AnQi CMS, for security reasons, defaults to escaping the content output to templates to prevent security vulnerabilities such as cross-site scripting (XSS).To safely display HTML or JS code in a template without being escaped

2025-11-08

How to manage and display the homepage banner carousel?

The homepage banner carousel is the face of the website, which not only attracts the attention of visitors in the first place, but also an important carrier for conveying brand information and promoting core products or services.In AnQiCMS, managing and displaying the homepage banner carousel is a straightforward and flexible process, allowing you to easily create an eye-catching visual focus for your website. ### One, manage your Banner content in the background To manage the homepage Banner carousel, you first need to log in to the AnQiCMS backend management interface. Usually

2025-11-08

How to remove extra spaces or characters from a string before displaying content?

During the operation of a website, we often encounter unnecessary spaces, line breaks, or special characters in the content. These 'impurities' not only affect the appearance of the content and the user's reading experience, but may also have a negative impact on the layout of the page and search engine optimization (SEO).AnQiCMS (AnQiCMS) is an efficient content management system that provides flexible and powerful template functions, among which the built-in template filters are the tools to solve such problems.Before you display content on the page, clean the string

2025-11-08

How to debug variables in a template and display their structure and values?

During the development and maintenance of website templates, we often encounter such situations: a page element does not display as expected, or data seems missing or incorrectly formatted.This is the key to quickly locate the problem, as you can clearly view the structure and specific values of variables in the template.For users who use AnQiCMS, the system provides powerful and convenient debugging tools to help us easily "penetrate" template data.Why do we need to debug template variables? Data is passed through variables in the AnQiCMS template.

2025-11-08

How to convert the original image address to a thumbnail address for display?

In modern website operations, images play a crucial role, not only enhancing the attractiveness of the content but also effectively conveying information.However, very large image files can significantly slow down website loading speed, harm user experience, and even affect search engine rankings.Therefore, converting the original image address to an optimized thumbnail address for display is an important part of website performance optimization.AnQiCMS as an efficient content management system fully considers the needs of image processing, built-in powerful thumbnail generation and management functions.Configure and template calls reasonably

2025-11-08

How to customize the layout and content display of the article detail page in AnQi CMS?

AnQiCMS (AnQiCMS) is a highly flexible content management system that provides great freedom to content operators, especially in customizing the layout and content display of article detail pages.Understanding the underlying mechanism and operation methods can help us better create personalized pages that meet user needs and optimize SEO performance.Why do you need a custom article detail page?In website operation, the article detail page is not only a carrier of content, but also a key touchpoint for users to deeply interact with information and achieve conversion goals.The standardized template is convenient and fast

2025-11-08