How to limit the display length of the link text when converting URLs with the `urlizetrunc` filter?

Calendar 👁️ 67

In AnQiCMS (AnQiCMS) content operation practice, we often encounter some details that require fine-grained processing, one of which is how to elegantly display the long URL on the page.When a long URL is included in the text of an article, user comment, or product description, it may destroy the page layout and affect the overall aesthetics and the reading experience of users.Luckyly, Anqi CMS providesurlizetruncA filter that helps us easily solve this problem, allowing the URL to be converted into a clickable link while also controlling its display length.

Why is it necessary to limit the display length of URLs?

Imagine if you had a technical article on your website that referenced a deep path link to a GitHub repository, or if a product parameter description contained a complex link to an external API document.These links are usually very long. When they are displayed directly on the page, they may cause the following problems:

  1. Visual confusion:Long URLs make the page look redundant and untidy.
  2. Layout destruction:In responsive design, long URLs are prone to overflow the container, especially on mobile devices, causing page elements to be misaligned.
  3. Poor reading experience:The user is interrupted by a long URL while reading, reducing the fluidity and readability of the content.
  4. Professionalism is受损:A tidy and standardized page can better reflect the professionalism of the website and attention to detail.

Anqi CMS knows the importance of content presentation, its template engine built-inurlizetruncThe filter is designed to solve such pain points, aiming to enhance user experience and website professionalism.

urlizetruncFilter: Intelligent Truncation and Link Conversion

urlizetruncIt is a very practical template filter, its core function is to automatically recognize and convert URLs or email addresses in plain text into clickable HTML<a>Label. And with its brother filterurlizeWhat is different is,urlizetruncAllow us to specify the display length of the converted link text. This means that regardless of the length of the original URL, only the number of characters you set will be displayed on the page, and the part exceeding it will be automatically abbreviated with an ellipsis (...This replaces, but the actual link target is still completehrefThe attribute is still the complete original URL

It is worth mentioning that in order to follow SEO practices,urlizetruncWhen converting a URL to a link, it will also automatically add these external linksrel="nofollow"Property. This helps to inform the search engine not to pass the 'weight' to these links, which is a very useful feature when managing external links, especially user-generated content links.

How to use it in Anqi CMS templateurlizetrunc

UseurlizetruncThe filter is very intuitive, you can apply it to any text variable containing a URL

Basic syntax formatAs follows:

{{ 你的文本变量 | urlizetrunc:指定长度 }}

Here指定长度Is an integer representing the maximum number of characters you want the link text to display, including any ellipses.

Application Example:

Assuming you have a document description variable.archive.DescriptionWhere it may contain various URLs. You want these URLs to be converted to links on the page, and to be displayed with a length not exceeding 25 characters. You can use it in the template like this:

<p>{{ archive.Description | urlizetrunc:25 | safe }}</p>

Please note that,urlizetruncAfter that, we usually follow with using|safeThe filter. This is because the Anqie CMS template engine, in order to prevent cross-site scripting (XSS) attacks and other security issues, defaults to escaping all output content with HTML entities and thenurlizetruncThe filter generates HTML code (<a>Tag), if you do not use|safeThese generated HTML codes will be escaped, and finally displayed on the page as plain text, not as clickable links.|safeThe function is to inform the template engine that this part of the content has been processed and is safe, and can be directly rendered as HTML.

If you need to process a large block of text rather than a single variable, you can also usefilter/endfilterTag pairs:

<div class="article-content">
    {% filter urlizetrunc:30 | safe %}
        这篇文章包含了一些重要的参考链接:
        https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/a
        还有一个非常长的API文档地址:
        http://api.example.com/v1/products/categories/electronics/subcategories/laptops/specifications?version=2.0&lang=en
        欢迎通过邮箱联系我们:[email protected]
    {% endfilter %}
</div>

In the above example, all identified URLs and email addresses will be converted to links and automatically truncated to no more than 30 characters of display text.

Practical suggestions

  • Length selection:There is no perfect 'magic number' that applies to all situations.It is recommended that you test on different pages and devices to find the length that best suits your website style and user experience.For a common URL, 15 to 25 characters is usually a good starting point.
  • Application scenario:In addition to the article content,urlizetruncit is also very suitable for handling user comments, messages, friend link descriptions, and other scenarios where long URLs may occur.
  • Maintain consistency:Maintain consistency throughout the entire website.urlizetruncConsistency in truncation length helps enhance the overall professionalism and user experience of the website.

ByurlizetruncFilter, Anqi CMS allows content operators to focus more on content creation and layout, without worrying about the display issues caused by long URLs.It not only simplifies link management, but also provides strong support for the cleanliness and user-friendliness of the website.


Frequently Asked Questions (FAQ)

Q1:urlizetruncandurlizeWhat are the main differences of the filter?

A1: urlizeandurlizetruncCan convert URLs and email addresses in text to clickable HTML links and automatically add themrel="nofollow"properties. The main difference between them is,urlizetruncAllow you to specify the maximum display length of the link text through a parameter, the part exceeding it will be automatically truncated and displayed with an ellipsis (...),whileurlizeIt will display the full URL text. Which filter to choose depends on whether you need to limit the display length of the link.

Q2: Why did I useurlizetruncFilter, but the links displayed on the page are still plain text and not clickable?

A2:This is usually because you forget tourlizetruncAdd after the filter|safeFilter. The template engine of AnQi CMS defaults to escaping all HTML code for security reasons to prevent XSS attacks.urlizetruncThe generated is HTML<a>Label, if it is not used for the result|safeThese HTML codes will be escaped and displayed as plain text. Add|safeAfter that, you clearly tell the template engine that this part of the HTML is safe and can be rendered directly.

Q3:urlizetruncThe filter automatically adds attributes to external links.rel="nofollow"What are the benefits of this attribute?

A3:Yes,urlizetruncThe filter will automatically add when converting a URL to a linkrel="nofollow"Properties. This is very beneficial for SEO, especially for links in user-generated content on websites (such as comments, forum posts).nofollowThe attribute tells the search engine not to pass 'weight' or 'reliability' to these links, thereby helping the website to better control its link assets, avoid unnecessary SEO risks, and also prevent the appearance of spam links.

Related articles

How does AnQiCMS automatically identify URL links in text and convert them into clickable `<a>` tags?

During content creation and publication, we often encounter situations where we need to cite external sources or share relevant links.If these URLs are in plain text form, users not only need to manually copy and paste them, but it will also affect the reading experience and the professionalism of the website.Anqi CMS knows this pain point, and therefore integrated the intelligent URL automatic recognition and conversion function from the beginning of the system design, making your content publishing more efficient and convenient, and improving the user experience accordingly.### Intelligent recognition, automatic conversion: Say goodbye to manual operation AnQi CMS through its powerful template engine

2025-11-08

What is the difference between the `urlencode` and `iriencode` filters in URL escaping?

In the daily content operation and website development of Anqi CMS, we often need to handle URL links to ensure that they are both secure and effective, and can be correctly parsed by browsers and search engines.This is an indispensable part of URL escaping (also known as encoding).Our Anqi CMS provides us with two very practical filters: `urlencode` and `iriencode`, both of which can help us with URL escaping, but their purposes and processing methods are different in actual application.###

2025-11-08

How to encode URL parameters to ensure the correctness and security of the link?

In the daily operation of Anqi CMS, we often need to deal with various website links, which not only need to be beautiful and SEO-friendly, but more importantly, they must work correctly and safely.Among these, encoding URL parameters is a seemingly trivial but crucial link, which is directly related to the integrity and user experience of our website links.Why is URL parameter encoding so important?Imagine if your website had a search function, and users entered keywords containing spaces, special characters, or even Chinese characters, such as "Anqi CMS"}

2025-11-08

Does the `first` and `last` filter return a single Chinese character when processing Chinese string?

In Anqi CMS template development, we often use various filters (filters) to format or extract data.The `first` and `last` filters are among the most common ones, used to get the first or last element from a string or array.Many friends who use AnQi CMS may be curious, when we process data containing Chinese characters, such as article titles or content snippets, will these two filters return single Chinese characters?The answer is: **Yes, the `first` and

2025-11-08

What are the differences between `trim`, `trimLeft`, and `trimRight` filters in removing whitespace or specific characters from a string?

In website content management, we often encounter situations where we need to clean and format strings, such as removing extra spaces at the beginning and end of user input text, or standardizing data with specific prefixes or suffixes.AnQiCMS provides a series of powerful template filters to simplify these operations, among which `trim`, `trimLeft`, and `trimRight` are powerful tools for handling string leading and trailing characters.They have similar functions but have different scopes.

2025-11-08

How to use the `slice` filter to extract a specified range of characters or elements from a string or array?

In the process of creating AnQiCMS templates, it is essential to be able to flexibly handle strings and arrays.Whether it is to display the article summary or to extract part of the elements from the list, the `slice` filter can provide powerful and convenient help.It allows you to extract specific ranges of characters from strings or select elements from arrays at specified positions, making content display more accurate and diverse.What is the `slice` filter?In simple terms, the `slice` filter is like a precise pair of scissors

2025-11-08

The `stringformat` filter provides which advanced string formatting options (such as number precision, alignment style)?

In the powerful template system of AnQi CMS, we often need to present dynamic data on the website, and the way data is displayed directly affects user experience and the efficiency of information communication.To present numbers, text, and other content in a more professional and clear manner, AnQi CMS provides the `stringformat` filter, which is a multifunctional formatting tool that helps us finely control the display details of content.The `stringformat` filter plays a role in AnQi CMS similar to the `fmt` in Go language

2025-11-08

How to repeat a string a specified number of times, for example, to display a welcome message repeatedly?

In website content operations, we often encounter situations where we need to repeat certain information, such as repeating copyright information in the footer, playing a greeting phrase in the welcome area repeatedly, or adding visual separators between list items.Copying and pasting manually is not only inefficient but also very麻烦 when it needs to be modified.Luckyly, AnQiCMS's powerful template engine provides a simple and efficient way to solve this problem, one very practical feature is the `repeat` filter.###

2025-11-08