How to use a filter to automatically find URLs in text and convert them into clickable HTML links?

Calendar 👁️ 74

In website operation, we often encounter such needs: in the article content or description text, there may be some website addresses or email addresses, but they are just plain text, and users cannot directly click to access them.Manually adding HTML links to each URL is not only inefficient but also prone to errors, especially when the volume of content is large.AnQiCMS (AnQiCMS) is fully aware of this pain point and provides a powerful built-in filter that can help us easily implement the automatic conversion of URLs in text, making website content more friendly and convenient.

Automated link: The key to enhancing user experience

Imagine, when a user is browsing your article and sees an interesting website, if they need to manually copy and paste it into the browser to open it, this undoubtedly increases the operation cost and reduces the reading experience.If these URLs can be automatically converted into clickable links, users can simply click on them to jump to the target page, which will greatly enhance the ease of use and professionalism of the website.The filter function of AnQi CMS is exactly for this.

Get to know the core tools:urlizeandurlizetruncFilter

In the Anqi CMS template system, filters play a role in processing and formatting variable content. They are usually through the pipe character|Connect after the variable to realize various functions. To convert URLs in text to clickable links, we mainly use two very practical filters:urlizeandurlizetrunc.

1.urlizeFilter: Automatically identify and convert to links

urlizeThe filter can intelligently identify URLs contained in a piece of text (includinghttp:///https://starting with, orwww.Prefixes, even those in pure domain name form), and email addresses, and automatically wrap them in<a href="...">tags to make them clickable links.

Working principle:WhenurlizeThe filter processes text and looks for string patterns that match URLs or email formats. Once found, it generates the corresponding<a>Label. It is worth noting that in order to comply with SEO **practices,urlizethe generated links will be added withrel="nofollow"attributes, which helps to avoid unnecessary "link weight" loss.

Usage example:Assuming your article content (or other text field) includes the following plain text URLs and email addresses:请访问我们的官网 https://en.anqicms.com 或发送邮件至 [email protected] 获取帮助。您也可以尝试 anqicms.cn。

In your Anqi CMS template, it is usually like this to call the article content variable and cooperateurlizeFilter:

{# 假设 articleContent 是包含上述文本的变量 #}
{{ articleContent|urlize|safe }}

Effect display:afterurlizeAfter the filter is processed, the following HTML will be rendered on the page:safeThe filter is to ensure that the HTML code is correctly parsed by the browser and not displayed as plain text:

请访问我们的官网 <a href="https://en.anqicms.com" rel="nofollow">https://en.anqicms.com</a> 或发送邮件至 <a href="mailto:[email protected]">[email protected]</a> 获取帮助。您也可以尝试 <a href="http://anqicms.cn" rel="nofollow">anqicms.cn</a>。

At this point, users can directly click on these links and email addresses.

2.urlizetruncFilter: Elegant Display of Long Links

When the URL contained in the text is particularly long, displaying the complete link directly may破坏 the aesthetics of the page layout.urlizetruncFilter is onurlizeOn the basis of this, a truncation feature has been added, which allows you to specify the maximum display length of the link text. If the length of the original URL string exceeds the value you set, it will be truncated and appended with...Thus, the page remains neat.

Working principle: urlizetruncwithurlizeThe core recognition mechanism is the same, but there is an additional parameter to control the display length. You need to provide a number representing the maximum number of characters of the link text.

Usage example:Assuming your article contains a very long URL:这是一个很长的链接,指向了我们的产品页面:https://en.anqicms.com/products/category/detail/long-product-name-with-many-words.html,欢迎查看。

If you want to truncate this link to display a maximum of 30 characters (including...), you can use it in the template like thisurlizetruncFilter:

{# 假设 articleContent 包含上述长链接文本 #}
{{ articleContent|urlizetrunc:30|safe }}

Effect display:After rendering to the page, you will see a simpler link display:

这是一个很长的链接,指向了我们的产品页面:<a href="https://en.anqicms.com/products/category/detail/long-product-name-with-many-words.html" rel="nofollow">https://en.anqicms.com/products/categ...</a>,欢迎查看。

This preserves the availability of the link while avoiding the impact of long links on page layout.

In the actual application of the Anqi CMS template

These filters can be used in any part of the Anqi CMS template where text content needs to be output, for example:

  • Article detail page (tag-/anqiapi-archive/142.html): When displaying document content (Content) or document description (Description).
    
    <div class="article-content">
        {{ archive.Content|urlize|safe }}
    </div>
    
  • Category detail page (tag-/anqiapi-category/152.html): Displaying category description (Description) or category content (Content).
    
    <p class="category-description">
        {{ category.Description|urlize|safe }}
    </p>
    
  • Single page detail page (tag-/anqiapi-category/153.html): Displaying single page content (Content) Or single page description (Description).
    
    <div class="page-content">
        {{ page.Content|urlizetrunc:50|safe }}
    </div>
    
  • Other custom text fieldIf you add custom text fields in the background content model and expect these fields to contain URLs, you can also apply to these fieldsurlizeorurlizetruncfilter.

Important reminder:Remember tourlizeorurlizetruncAdd after the filter|safefilter was used. This is becauseurlizeVariants generate HTML code, and for security reasons, the Anqi CMS template engine defaults to escaping all output content (which converts<to&lt;Prevent cross-site scripting attacks (XSS).|safeThe filter clearly tells the template engine that this content is safe HTML and does not need to be escaped, and can be rendered directly.

Summary

ByurlizeandurlizetruncThese simple yet powerful filters greatly simplify the management of URL text in the website content of AnQi CMS.They not only enhance the user experience of the website, making the content more interactive, but also help operators to maintain readability of the content while taking certain SEO considerations into account.In daily operations, flexibly using these filters can make your website content management more efficient and professional.


Frequently Asked Questions (FAQ)

Q1: Why did I useurlizeAfter the filter, is the text still displayed on the page in plain text, rather than clickable links?

A1:This is usually because you forget tourlizeAdd after the filter|safeFilter. The AnQi CMS template engine defaults to escaping all output content to prevent potential security risks (such as XSS attacks).urlizeThe filter generates HTML code (<a>tag), if not added|safethese tags will be escaped as.<a>The tag itself will be escaped into plain text, causing the link to be unclickable. Make sure your code is similar to{{ 您的内容变量|urlize|safe }}.

Q2:urlizeDoes the filter support recognizing and converting Chinese URLs?

A2: urlizeThe filter mainly relies on recognizing URL protocols (such ashttp:///https://) and structures (such aswww.、domain suffixes, etc.). For URLs containing Chinese paths or parameters, as long as the overall structure conforms to the URL specification and has been URL encoded, theoreticallyurlizeThe filter can recognize and convert it to a link. However, when displayed in actuality, especially when usingurlizetruncWhen truncating, the truncation effect of mixed Chinese and English URLs may need to be adjusted according to the specific situation to ensure aesthetics and readability.

Q3:urlizeAll links generated by the filter containrel="nofollow"Property, can I customize or remove this property?

A3: urlizeThe filter, in order to consider the default SEO (to prevent weight loss), will automatically add the generated link.rel="nofollow"If your operation strategy needs to removenofollowattributes or add other custom attributes, then throughurlizeThe filter itself cannot be configured directly. In this case, you need to consider manually writing HTML links in the template, or using other features of the Anqi CMS backend (such as anchor text management, if it supports more flexible link attribute configuration), rather than relying on it completelyurlizeThe filter performs automated processing.

Related articles

How to use a filter to remove specific characters (such as spaces) from the beginning, end, or any position of a string?

String cleaning practical guide in AnQiCMS: Efficiently remove filters for specific characters During the operation of a website, we often encounter situations where we need to clean and format string data.Whether it's the extra spaces typed by users or redundant characters carried in when importing content from external sources, these subtle details may affect the neatness of website content and the user experience.AnQiCMS (AnQiCMS) provides a multifunctional and easy-to-use template filter that can help us easily deal with these string cleaning needs.

2025-11-08

How to set a default display value for a possibly empty variable, string, or object?

In website content management, the integrity and consistency of data are crucial.However, in actual operation, we often encounter situations where certain variables, strings, or objects may be empty.If the template does not handle these null values properly, the front-end page may appear blank, disordered, or even report errors, severely affecting user experience.AnQiCMS provides various flexible and powerful template tags and filters, helping us elegantly handle potential null values to ensure the stability and beauty of website content.The AnQi CMS template system borrows the syntax from Django

2025-11-08

How to perform addition or other arithmetic operations on numbers or strings in the template?

In website template development, we often need to perform some basic arithmetic operations, such as calculating the sum, adjusting values, or comparing values based on specific conditions.AnQiCMS (AnQiCMS) boasts an efficient architecture based on the Go language and a flexible template engine inspired by the Django style, providing users with an intuitive and powerful way to perform arithmetic operations such as addition of numbers or strings in templates.

2025-11-08

How to use a filter to truncate the specified character length of an article description or abstract and automatically add an ellipsis?

In website operation, the presentation of article description or abstract is crucial for user experience and Search Engine Optimization (SEO).A well-balanced, concise summary that not only attracts visitors to click but also helps search engines better understand the page content.However, manually controlling the length of each article summary is time-consuming and prone to errors.Fortunately, AnqiCMS provides powerful template filter functions that can help us automate this process, ensuring the uniformity and beauty of website content display.Why is it necessary to truncate article descriptions or summaries

2025-11-08

How to ensure that HTML code is correctly parsed and not escaped when displaying rich text content using the `safe` filter?

In AnQi CMS, rich text content usually carries articles, product descriptions, or page details with rich information. This content often includes various HTML tags such as bold, italic, images, links, tables, and so on.If this HTML code is not parsed correctly and is simply displayed as plain text, then what the user sees on the front end is a pile of code, rather than beautiful and structured content. This clearly has a negative impact on the readability and professionalism of the website.

2025-11-08

If the article content is in Markdown format, how to use the `render` filter to render it as HTML?

AnQi CMS is favored by many users for its efficient and flexible content management capabilities.In content creation, Markdown format has become the preferred choice for many content creators due to its simplicity and efficiency.But how to beautifully present these Markdown-formatted contents as structured HTML on the website front-end is a concern for many users.

2025-11-08

How to dynamically output the SEO title, keywords, and description (TDK) on AnQiCMS templates?

The performance of a website in search engines directly affects the efficiency of content access, and the title (Title), keywords (Keywords), and description (Description), abbreviated as TDK, are the 'business card' for search engines to understand page content.Effectively manage and dynamically output TDK, which can significantly improve the SEO effect and click-through rate of the website.AnQiCMS is a content management system that highly values SEO and provides flexible and powerful features, making it easy to dynamically configure page TDK.

2025-11-08

How to use the `languages` tag to build a language switch menu and output the `hreflang` tag in a multilingual site?

Building multilingual sites in AnQiCMS (AnQiCMS) can not only expand your market range but also provide a more user-friendly access experience for users in different regions.To achieve this goal, the core lies in effectively utilizing the `languages` tag to create a language switch menu and correctly output the `hreflang` tag to optimize search engine recognition.AnQiCMS is a content management system that focuses on enterprise applications, with its powerful multilingual support being one of its highlights.It allows you to create multiple language versions for website content

2025-11-08