In the AnQiCMS template, we often encounter such a scenario: we hope to automatically convert URLs or email addresses appearing in text content into clickable links without manually writing them<a>Label. It not only improves the user's browsing experience, but also makes our content more interactive. AnQiCMS's powerful template engine providesurlizeFilter, can easily meet this requirement, and it can be applied flexibly at any position in the template.

Get to knowurlizeThe role of the filter and its effects

urlizeA filter is a very practical tool, its main function is to automatically identify the URL addresses in a piece of text (such ashttp://www.anqicms.com/www.anqicms.comevenanqicms.com) and email addresses, and wrap them in HTML's<a>tags to make them clickable links. It is also worth mentioning that it will automatically add these external linksrel="nofollow"Properties, this is a good practice for search engine optimization (SEO) and can avoid unnecessary weight passing.

In addition to basic URL conversion,urlizeIt supports a parameter to control the HTML escaping of the link text:

  • urlize:true: The displayed text of the link will be HTML escaped. For example, if the link contains"Characters, they will be converted to&quot;.
  • urlize:false: The display text of the link is not escaped by HTML, it retains the original characters directly. Usually, we tend to useurlize:falseOr without parameters, to maintain the original display of the link text.

Why is it needed|safeFilter?

Further understandurlizeBefore using the method, there is a very important concept that needs to be mastered in advance:|safeFilter. AnQiCMS's template engine defaults to HTML-escaping all output variables, which is a security measure designed to prevent cross-site scripting attacks (XSS).This means, ifurlizeThe filter has generated<a href="...">...</a>Such HTML structure, the system will treat it as plain text and escape it as&lt;a href="..."&gt;...&lt;/a&gt;This causes the link to not display normally.

In order tourlizeThe generated HTML tags can be correctly parsed by the browser, and we must follow it closely with|safeThe filter explicitly tells the template engine: this content is safe and does not require HTML escaping. Therefore, when usingurlizeyou will usually see{{ 变量 | urlize | safe }}such combinations.

How to use in the templateurlizeFilter?

urlizeThere are two main uses of the filter, which can meet your needs at different positions in the template:

1. Inline conversion of a single variable

This is the most common usage, when you need to convert a URL (such as article description, custom field content) into a link, you can directly use the pipe symbol in the output variable|Invokeurlize.

Usage example:

Assume you have an article objectitemof whichitem.DescriptionThe field may contain some URLs.

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

This code will checkitem.DescriptionThe text, convert all detected URLs or email addresses into clickable links, and ensure that these HTML tags are correctly rendered by the browser.

If you want to see the effect of escaping link text (usually not recommended, but it is important to understand its behavior):

{# 链接文本中的特殊字符会被转义 #}
<p>{% set content = "访问我们的网站 www.anqicms.com/test?param=\"value\" 获取更多信息" %}
{{ content | urlize:true | safe }}</p>

Hereurlize:trueMeans to escape the displayed text of the link itself.

2. Convert label block content in bulk

When you want to perform URL encoding on a larger area of the template, which includes multi-line text, even static text and mixed dynamic variables, you can use{% filter urlize %}Label block. This label block will treat all the text content inside it as a whole, applying it uniformlyurlizeFilter. This is the key to applying URL conversion at any location in the AnQiCMS template.

Usage example:

Assuming you have a custom sidebar module that includes some contact information submitted by users, or some hard-coded external resource links.

<div class="sidebar-contact-info">
    <h3>联系我们</h3>
    {% filter urlize | safe %}
        欢迎访问我们的官网:http://www.anqicms.com
        或者发送邮件至:[email protected]
        你也可以关注我们的GitHub项目:github.com/fesiong/goblog
        我们的电话是:+86-1234567890 (这个不会被转换,因为它不是URL或邮箱格式)
        {% set custom_url = "https://docs.anqicms.com/help-index.md" %}
        查阅帮助文档:{{ custom_url }}
    {% endfilter %}
</div>

in this{% filter %}Inside the block, no matter what static text you write or through{{ }}the output variable, as long as it is a string that matches the URL or email format, it will beurlizeconverted to a link. Similarly,|safeThe filter is indispensable, ensuring that the entire converted HTML content can be displayed normally.

urlizetrunc: Elegant handling of long links.

In some cases, the converted URL may be very long, affecting the aesthetics of the page. AnQiCMS providesurlizetruncA filter that performsurlizeSimilar, but it allows you to specify a length, if the displayed text of the link exceeds this length, it will be truncated and...it indicates an omission.

Usage example:

<p>以下是一些长链接示例:</p>
{% filter urlizetrunc:25 | safe %}
    这是一个超长的链接:http://www.example.com/very/long/path/to/some/resource/with/many/parameters?id=123&token=abcde
    另一个链接:https://anqicms.com/category/1/article/1234567890/detail.html
{% endfilter %}

In this example, the display text of each converted link (not the actualhrefproperty) will be truncated if it exceeds 25 characters.

Application scenarios and precautions

  • Dynamic content output:The most common scenario is when outputting article content, product descriptions, category summaries, single-page content, or any custom field. For example, when you usearchiveDetailtags to retrieve document content:
    
    <div>
        {%- archiveDetail articleContent with name="Content" %}
        {{ articleContent | urlize | safe }}
    </div>
    
  • User-generated content:For comments, message boards, user profiles, and other user-submitted content, useurlizeCan greatly enhance its usability. However, be cautious when dealing with user-generated content.|safeBecause it will bypass the default HTML escaping. Althoughurlizeit will generatenofollowProperties, but when used before or after other filters, it is still necessary to ensure the overall safety of the output.
  • Simple display of the list page:In the short description of the article list, product list, if it contains a URL, it can beurlizeclickable quickly to improve the efficiency of information acquisition.
  • Global text block:For text content in fixed areas such as footers, sidebars, etc., if it contains URLs, use{% filter urlize %}a block to solve the conversion problem in one go.

Important reminder:

  • |safeMust not be omitted:Emphasize again,urlizeThe HTML tag is generated, if not配合|safeThese tags will be output as plain text, links will not work.
  • Avoid repeating on HTML content that is already present:If your content is already structured HTML (for example, from a rich text editor), apply it again.urlizeMay result in unexpected outcomes, even destroying the original structure. UsuallyurlizeSuitable for plain text content.
  • nofollowattribute:AnQiCMS automatically adds forurlizelinks generated by addingrel="nofollow"This is a good practice for handling external links, which helps maintain the SEO performance of the website.

By flexible applicationurlizeFilter, AnQiCMS users can greatly simplify the template development process, enhance the accessibility and interactivity of content, while also considering the safety and SEO-friendliness of page output.

Frequently Asked Questions (FAQ)

1.|safeWhat is the use of the filter, when is it necessary to use it?

|safeThe filter tells the AnQiCMS template engine that the HTML code output by the variables or tags before it is safe and does not require the default HTML escaping. It isit mustUse after any filter that outputs HTML tags (such asurlize/linebreaksetc.), so that these HTML tags are parsed and rendered correctly by the browser. For example,urlizeThe filter will also treatwww.example.comConvert to `<a href=“http