How to safely parse a URL string into a clickable a tag in AnQiCMS template?

Calendar 👁️ 70

In website content operation, we often need to display some website addresses, email addresses, and other information in articles, summaries, or custom fields.If this information is just plain text, users cannot directly click to jump, which not only affects the user experience but may also reduce the interactivity of the content and the SEO friendliness of the website.<a>Label, it is a very practical feature in the AnQiCMS template.

AnQiCMS as an enterprise-level content management system has fully considered the flexibility and security of content display from the very beginning. Its template engine provides a rich set of filter (Filters) functions, whereurlizeandurlizetruncThese filters are exactly the tools to solve our problem.

Smart useurlizeThe filter will make the URL intelligent.

urlizeA filter is an extremely intelligent tool. When you have a piece of text content that may contain various formats of URLs (such ashttp://www.example.com/https://example.org/www.example.netevenexample.co) or email addresses ([email protected])urlizeCan automatically identify them and generate standard HTML for these strings<a>Tags to make them clickable links on the page.

It is particularly worth mentioning that, for SEO and security reasons, AnQiCMS'surlizeThe filter automatically appends when generating external links,rel="nofollow"property.This means that search engines usually do not pass weight to the target website when crawling these links, which helps to avoid unnecessary SEO risks and also protects the link health of the website.

To use it, you just need to pass the variable containing the URL through the pipe|Connected tourlizefilter. For example, if your document summary contains a URL, you can handle it like this in the template:

<p>{{ archive.Description|urlize }}</p>

However, it is not enough to write it like this.AnQiCMS's template engine defaults to enabling automatic escaping functionality, which is to prevent cross-site scripting (XSS) and other security issues.urlizeThe filter generated HTML code (for example<a>Tags), without any additional declarations, these HTML codes will be displayed as plain text instead of rendering actual links. Therefore, in order for the browser to correctly parse and display clickable links, we also need to use in conjunction with|safefilter.

So, the correct usage should be:

<p>{{ archive.Description|urlize|safe }}</p>

|safeThe filter's role is to inform the template engine that this part of the output content is "safe", and it does not require HTML entity escaping. It can be rendered directly as HTML code on the page.

urlizetrunc: Graceful handling of long URLs

In some cases, the URL string in the text may be very long, and displaying it in full may affect the aesthetics of the page layout. At this time,urlizetruncThe filter comes into play.

urlizetruncfunction withurlizesimilar, it can also recognize URLs in text and generate clickable ones<a>The label provides an additional parameter that can specify the display length of the link text. If the length of the original URL exceeds the value you set,urlizetruncan ellipsis will be added at the end of the truncation...), so that the link appears more concise.

UseurlizetruncWhen, you need to add a colon after the filter and specify the character length you want to display. For example, if you want the link text to display a maximum of 30 characters:

<p>{{ customFieldContent|urlizetrunc:30|safe }}</p>

This is particularly useful for displaying text containing URLs in limited space (such as sidebars, list summaries, or card views), as it maintains the clickable nature of the links while also keeping the page neat.

Application scenarios and **practice

In AnQiCMS, you can use these filters in templates for various content types:

  • Article detail page (archiveDetail): Process URLs in article content, summaries, or custom fields.
    
    <div>
        {%- archiveDetail articleContent with name="Content" %}
        {{ articleContent|urlize|safe }}
    </div>
    
  • Single page (pageDetail)Translate the URLs in the 'About Us', 'Contact Us', and other single-page content to links.
    
    <div>
        {% pageDetail pageContent with name="Content" %}
        {{ pageContent|urlize|safe }}
    </div>
    
  • Category description (categoryDetail)Make the URLs or email addresses clickable in the description text of the category page.
    
    <div>
        {% categoryDetail categoryDescription with name="Description" %}
        {{ categoryDescription|urlize|safe }}
    </div>
    
  • Custom content field: If your content model defines custom fields that include URLs, this applies as well.
    
    {% archiveDetail productLink with name="ProductLink" %}
    <p>产品链接:{{ productLink|urlizetrunc:50|safe }}</p>
    

Remember the following points **practical** when using these filters:

  1. Always cooperate|safeUse:urlizeandurlizetruncThe HTML code generated, in order for the browser to correctly parse these codes, it must be added after them|safeFilter. It is the key to ensure that the link displays normally and the operation after confirming the content safety.
  2. Consider displaying the environment selection filter: If there is ample display space,urlizeCan provide complete link information; if space is limited,urlizetruncthen it can help you elegantly manage the display of long URLs.
  3. Understandingrel="nofollow":urlizeAutomatically addednofollowIt is a default security and SEO mechanism, if you have special requirements to remove or change this attribute, you may need to do deeper development on the backend or find other solutions. However, for most external links,nofollowIt is usually recommended.

AnQiCMS usesurlizeandurlizetruncThe filter provides a convenient and secure way for content operators to convert URL strings in text to clickable HTML links, thereby enhancing the user experience of the website, improving the accessibility of information, and maintaining good SEO practices.Master these filters and your content will be more vivid and practical.


Frequently Asked Questions (FAQ)

1. Why did I useurlizeAfter that, it was directly displayed on the page.<a href="...">...</a>Is this HTML code, not a clickable link?

This is usually because you forgot tourlizeAdd after the filter|safeFilter. AnQiCMS template engine defaults to escaping HTML special characters to prevent XSS attacks.urlizeThe filter will generate HTML code, if this code is not marked assafe, the template engine will treat them as ordinary text and escape them for display. Add|safeAfter that, the template engine knows that this HTML content is confirmed to be safe and can be rendered directly.

2. UseurlizeandurlizetruncLinks are automatically added when generating links.rel="nofollow"Should I add the attribute?

Yes, AnQiCMS'urlizeandurlizetruncThe filter converts URLs in the text to<a>When labeling, it will automatically add external links (non-site domain) torel="nofollow"Property. This is a default SEO and security mechanism that helps manage the distribution of link weight on the website and reduce the risk of spam links.

3. BesidesurlizeandurlizetruncHow can I handle URLs or manually create links in AnQiCMS templates?

If the URL itself is a variable, and you want to customize it completely<a>The display style of the label, you can directly use HTML syntax combined with variables to create links, for example:<a href="{{ someVariableLink }}">{{ someVariableText }}</a>Please note that this method is suitable forsomeVariableLinkIt is a complete and ready-to-use URL.urlizeandurlizetruncThe advantage lies in their ability to automatically recognize and convertin the text string.The URL, especially when these URLs are mixed with plain text.

Related articles

How to implement the filtering function of the article list in AnQiCMS, displaying different results according to custom parameters?

How to make it easier for users to find the content they need on the website is the key to improving user experience and conversion rates.The filtering function of the article list is an important means to achieve this goal.AnQiCMS provides a flexible and powerful mechanism that allows us to easily filter and display different list results of articles based on custom parameters, which is very helpful for building personalized and efficient content platforms.### The Foundation of Building a Filtering Function: Custom Content Model To implement an article list filter based on custom parameters

2025-11-08

How to use a filter in AnQiCMS template to convert a timestamp to a readable date format?

In website operation, we often need to display various time information on the front-end page, such as the publication date of articles, content update time, or user comment time.AnQiCMS as an enterprise-level content management system usually adopts the efficient and concise format of Unix timestamps for data storage.However, for users visiting the website, a string of numeric timestamps is obviously not intuitive and friendly.How can I convert these timestamps into a readable date format in AnQiCMS templates?AnQiCMS provides a very practical built-in tag and filter

2025-11-08

How does AnQiCMS automatically extract the first image of the article content as a thumbnail?

In content operation, matching a suitable thumbnail for each article can not only enhance the visual appeal of the website, but also quickly attract users' attention in the information stream.However, manually uploading and adjusting thumbnails for each article, especially when the volume of content is large, is undoubtedly a time-consuming and labor-intensive task.AnQi CMS knows this pain point and provides an intelligent and efficient thumbnail automatic extraction mechanism, making content publishing more hassle-free.

2025-11-08

How to retrieve and display custom parameters of an article on the article detail page (such as author, source)?

Manage and display content in Anqi CMS, the article detail page is undoubtedly the core position for users to obtain information.In addition to basic elements such as article titles and text, we often need to display some personalized information on the detail page, such as the author of the article, source of content, product specifications, and release location, etc.This information is called "Custom Parameters" in Anqi CMS, which can greatly enrich the dimensions of content and meet the personalized needs of different business scenarios.The AnQi CMS provides a very flexible way to define and display these custom parameters, allowing website operators to meet their actual needs

2025-11-08

How to enable anti-crawling interference code and image watermark in AnQiCMS to protect the display of content?

In today's era of increasingly rich digital content, protecting original content on websites is particularly important.AnQiCMS (AnQiCMS) understands the pain points of content creators and corporate users, and has specifically built anti-crawling interference codes and image watermarking functions to help users effectively prevent their content from being maliciously scraped and stolen, while also strengthening brand identity.### Protect content security: Enable anti-capture interference code The value of original content is self-evident, but information collection tools on the Internet may copy your articles in large quantities without permission, which not only harms the rights and interests of the original creators but may also divert website traffic

2025-11-08

How to implement pagination display and like function for comment content in AnQiCMS?

In website operation, user comments and interaction are the key to enhancing the vitality of content.AnQiCMS (AnQiCMS) provides powerful content management capabilities, among which the comment feature is an important bridge for user interaction with content.This article will discuss in detail how to implement pagination for comment lists in Anqi CMS, as well as add a like function for comment content, enhancing the interactive experience of your website to a higher level.### CMS Review Function Overview The CMS has built-in article comment and comment management functions from the early version, which provides native user interaction support for the website

2025-11-08

How to debug variable content and type in AnQiCMS template (using dump filter)?

When using AnQiCMS to build websites and customize templates, we often encounter situations where the content displayed on the page is not as expected, or it seems that a variable is not passing correctly.At this moment, it is particularly important to be able to quickly view the actual content and data type of variables in the template.Fortunately, AnQiCMS's template engine (which adopts a syntax similar to Django) provides us with a very practical tool—the `dump` filter, which helps us easily reveal the mysteries of variables.### Core Function: `dump`

2025-11-08

How to call data from other sites in a multi-site environment using the siteId parameter?

In the multi-site environment of AnQiCMS, data intercommunication is a key factor in improving operational efficiency and achieving content integration.Sometimes, we may need to display the content of a sub-site on the main site, or call the contact information of another brand site in a business site.At this time, the `siteId` parameter provided by AnQiCMS is particularly important, as it helps us easily implement cross-site data calls and display.### Understanding the multi-site advantages of AnQiCMS AnQiCMS was initially designed with the need for multi-site management in mind

2025-11-08