The `urlize` and `urlizetrunc` filters: How to handle the display and truncation of long URLs?

Calendar 👁️ 72

In website content operation, we often need to handle various links, whether it is external resources cited in articles or websites left by users in comment sections.However, when these links are too long, they may not only disrupt the overall layout of the page, affecting its aesthetics, but may also reduce the reading experience of the users.Fortunately, AnQiCMS provides a pair of very practical filters——urlizeandurlizetruncThey can help us manage and display these long or unformatted URLs elegantly.

Say goodbye to manual copy and paste:urlizeThe magic of automatic linking.

Imagine you are creating content that requires referencing a large number of external websites or email addresses.If you had to manually copy the URL and then add a hyperlink through the editor each time, it would be such a cumbersome task.Not to mention users leaving plain text URLs in the comments, which is not only unattractive but also not convenient to click.

AnQiCMS'urlizeThe filter is exactly for solving these problems. Its core function is to convert plain text URLs (includinghttp:///https://those that start with the link,www.Links at the beginning, even naked domain names), as well as email addresses, are automatically converted to clickable HTML<a>.

For example, if you have a text that contains URLs:

<p>欢迎访问我们的网站:https://en.anqicms.com,或通过邮箱联系我们:[email protected]。</p>

afterurlizeAfter the filter is processed, cooperate|safeDeclare content security, it will become:

<p>{{ "欢迎访问我们的网站:https://en.anqicms.com,或通过邮箱联系我们:[email protected]。"|urlize|safe }}</p>

The output HTML will be:

<p>欢迎访问我们的网站:<a href="https://en.anqicms.com" rel="nofollow">https://en.anqicms.com</a>,或通过邮箱联系我们:<a href="mailto:[email protected]">[email protected]</a>。</p>

As you can see,urlizeNot only did it automatically create links, but it also intelligently added links to external linksrel="nofollow"Property. This property is very friendly to SEO, it tells the search engine not to pass the 'link weight' to these external links, which helps maintain the weight distribution of the website itself.

Furthermore,urlizeIt supports an optional parameter to control the escaping of link content. By default, the link text is escaped as HTML entities (equivalent totrue), such as in URLs."It will be converted into&quot;To ensure correct display in HTML. If you need to display the original URL string without escaping, you can explicitly set it tofalseThis is usually not recommended as it may pose potential security risks.

Gracefully truncate long links:urlizetruncaesthetics

urlizeThe filter is powerful, but it will display the full link text as is when processing very long URLs.In some cases, this may cause the page layout to expand or the link text to occupy too much space, especially on mobile devices, which will severely affect the user experience.

At this time,urlizetruncThe filter comes into play.urlizetruncfunction withurlizeSimilar, but it adds a key feature: it is possible to specify the maximum display length of the link text. When the displayed text of the original URL exceeds this length,urlizetruncIt will truncate and add at the end...But the underlyinghrefattribute still retains the complete URL.

For example, a long URLhttps://en.anqicms.com/category/anqi-cms-features-and-benefits/anqi-cms-template-development-guideIf we want it to display only the first 15 characters:

<p>{{ "访问此页面了解更多:https://en.anqicms.com/category/anqi-cms-features-and-benefits/anqi-cms-template-development-guide"|urlizetrunc:15|safe }}</p>

The output HTML might be:

<p>访问此页面了解更多:<a href="https://en.anqicms.com/category/anqi-cms-features-and-benefits/anqi-cms-template-development-guide" rel="nofollow">https://www.anqicms...</a></p>

Please note,urlizetruncWhat is truncated is:<a>Visible text within the tag, not the actual:hrefLink. When the user clicks, it will still jump to the full link address.This maintains the page neatness while also considering the practicality of the links.By reasonably setting the truncation length, we can ensure that the page maintains good visual effects on different devices.

Application scenarios and practical suggestions

These filters have widespread applications in daily website content management and operations:

  1. User comments and message area: Comments submitted by users may contain various formats of links. UseurlizetruncCan avoid malicious or long links from destroying the page layout while ensuring the clickable nature of legitimate links.
  2. Article content citation: When citing external sources in the text of the article,urlizeCan quickly convert URLs to links, saving editing time. If the link itself is very long,urlizetruncit can maintain the fluidity of the paragraph and avoid reading interruptions.
  3. Resource list or reference materialsIn displaying a series of external resources or references, especially when the title space is limited,urlizetruncit can make the list more organized and easy to browse.
  4. Social sharing and external linksWhen you need to display various social media links or partner links at the bottom or sidebar of the page, these two filters can quickly generate standardizednofollowLink and control its display length.

In summary, AnQiCMS'surlizeandurlizetruncThe filter is a tool to improve content operation efficiency and optimize user experience. By cleverly using them, we can easily manage the links on the website, making the page both beautiful and practical.


Frequently Asked Questions (FAQ)

1. Why did I useurlizeorurlizetruncFilter, but the original HTML tags (such as<a href="...">...</a>) are still displayed on the page instead of clickable links?

This is usually because you forgot to add|safe.AnQiCMS (and many template engines) for security reasons, the default is to escape all output content to HTML entities to prevent XSS attacks. Whenurlizeorurlizetruncgenerate<a>After the HTML tags, if missing|safeThese HTML codes will be escaped as strings and displayed, rather than parsed as actual links by the browser. Therefore, make sure that your template code is{{ content_variable|urlize|safe }}or{{ content_variable|urlizetrunc:number|safe }}.

2.urlizeandurlizetruncCan the filter correctly handle URLs containing Chinese or other non-Latin characters?

Yes, AnQiCMS's template engine is based on Go language and has good support for UTF-8 encoding. Therefore,urlizeandurlizetruncThe filter can correctly identify and handle URLs containing non-Latin characters such as Chinese, Japanese, and Korean.They will encode these URLs into a format recognizable by the browser (such as percent encoding) and create the correct link.

3.urlizeandurlizetruncThe filter adds by default,rel="nofollow"Can the attribute be removed or modified?

urlizeandurlizetruncThe filter is designed to simplify the handling of external links and follow SEO**practices, therefore it will automatically add to the generated external links by defaultrel="nofollow"Property. If you have special requirements, you want to remove or modify this property (for example, to pass link weight), these filters do not provide direct parameters to control.nofollowYou may need to use the following methods:

  • Manually create linksFor links where you explicitly want to pass weight, you can bypass the filter and manually write them in the template<a>Label and set as neededrelProperty.
  • Front-end JavaScript processing: Remove or modify these after the page loads with JavaScriptrelThis may cause uncertainty in SEO effects and is not a recommended long-term solution.
  • Backend custom logicIf you are a developer or have the ability to perform secondary development, you can preprocess the URLs in the content before template rendering through custom backend logic to achieve finer control.

Related articles

How to automatically recognize URLs in AnQiCMS templates and convert them into clickable hyperlinks?

In website operation, the flexibility of content display and user experience is crucial.We often need to display some external links or references in the content of articles, product descriptions, or various text areas.Manually adding the HTML `<a>` tag to each URL is not only inefficient but also prone to errors, especially when the amount of website content is large or needs to be updated frequently, which is undoubtedly a cumbersome task.AnQiCMS provides an elegant and efficient solution to this pain point.

2025-11-08

`removetags` and `striptags` filters: What is the difference and **choice** when clearing HTML tags?

When managing and presenting content in Anqi CMS, we often encounter a common need: how to elegantly handle HTML tags contained in the content.In order to display a concise summary on the article list page, provide clean meta descriptions for search engine optimization (SEO), or simply to avoid unnecessary style conflicts, removing or filtering HTML tags is a basic and important skill.Aqie CMS provides two powerful filters: `removetags` and `striptags`.

2025-11-08

How to control the alignment of a string within a specified width using `center`, `ljust`, and `rjust` filters?

In website content operation, the way content is presented often determines the first impression and reading experience of users.How to ensure that the text information displayed in the website template is uniform, beautiful, and professional, which is a concern for many operators.AnQiCMS as a content management system that focuses on user experience and highly customizable, deeply understands this, and its powerful template engine provides a variety of practical filters to help us easily align strings.

2025-11-08

`capfirst`, `lower`, `upper`, `title` filters: how to handle the need for English text case conversion?

In website content operation, the uniformity and beauty of text format are crucial for improving user experience.Especially when dealing with English text, flexibly controlling the case can help us better present information, whether it is used for headings, keywords, or body content.AnQiCMS provides a series of practical template filters to help you easily deal with various English case conversion needs.

2025-11-08

`repeat` filter: How to repeat a specified string N times to generate placeholder content?

In the world of AnQi CMS templates, we often need some flexible tools to quickly build page layouts or generate placeholder content when there is no actual data.The `repeat` filter is a feature that is not very noticeable but very practical, and it can help you output the specified string N times in a concise way. ### `repeat` filter: A practical technique for quickly generating repeated strings In website content management and template design, we often need to display a character, phrase, or even a short segment of HTML code repeatedly.For example, when you need a separator line

2025-11-08

The `random` filter: How to randomly select a character or element from a string or array?

In Anqi CMS template design, we often need to make the website content dynamic and random to avoid the content being too static and to enhance the browsing fun of users.When you want to randomly select one from a series of preset options, text, or data to display, the `random` filter is a very practical tool.It can help you randomly pick a character or element from a string or array (also known as a list or set), adding an element of unpredictability to your website content.

2025-11-08

The `wordwrap` filter: how to elegantly handle the automatic line break display of long text without truncating words?

In website content display, we often encounter layout problems with long text content.When a piece of text is too long and exceeds the container width, if it is not properly handled, it may cause layout disorder and a decline in reading experience.AnQiCMS (AnQiCMS) provides a very practical template filter - `wordwrap`, which helps us elegantly solve the automatic line break display of long text, and the key point is that it maintains the integrity of words, avoids cutting words in the middle, thereby greatly enhancing the professionalism and readability of the content.

2025-11-08

How to implement the unified or independent display of multi-site content on the AnQiCMS front end?

For users with multiple websites, brands, or content branches, how to efficiently manage and flexibly display content has always been a core challenge in website operations.AnQiCMS is a content management system designed for multi-site management, which not only provides a unified backend management interface, but also gives users great freedom in front-end content display, allowing for completely independent content display and easy unified calling and aggregation display across sites.Next, we will delve into how AnQiCMS implements these two seemingly opposing yet complementary content display strategies.

2025-11-08