In AnQiCMS templates, we often encounter such a scenario: we want to automatically convert the URL addresses or email addresses appearing in the text content into clickable links without manually writing them<a>Tags. This not only enhances the user browsing experience, but also makes our content more interactive. AnQiCMS's powerful template engine providesurlizeA filter that can easily meet this requirement and can be applied flexibly at any position in the template.

KnowurlizeThe filter and its function

urlizeA filter is a very practical tool, its main function is to automatically identify URL addresses in a piece of text (for examplehttp://www.anqicms.com/www.anqicms.comevenanqicms.com)and email addresses, wrapping them in HTML tags to make them clickable links. It's worth mentioning that it will also automatically add<a>tags, making them clickable links. It's worth mentioning that it will also automatically addrel="nofollow"[en]Property, this is a good practice for search engine optimization (SEO) and can avoid unnecessary weight transmission.

[en]In addition to basic URL transformation,urlizeIt supports a parameter to control the HTML escaping of the link text:

  • urlize:true: The display text of the link will be HTML escaped. For example, if the link contains"A character, which will be converted&quot;.
  • urlize:false: The display text of the link will not be escaped by HTML and will be retained as the original characters. Usually, we tend to useurlize:falseOr without parameters, to maintain the original display of the link text.

Why is it needed?|safeFilter?

Before getting a deeper understandingurlizeThere is an extremely important concept that needs to be mastered in advance:|safeFilter.AnQiCMS's template engine defaults to escaping all output variables as HTML, which is a security mechanism designed to prevent cross-site scripting (XSS) attacks.urlizeThe filter has generated<a href="...">...</a>This HTML structure is treated as plain text by the system and escaped as&lt;a href="..."&gt;...&lt;/a&gt;which causes the link to not display correctly.

In order tourlizeThe generated HTML tag can be correctly parsed by the browser, we must follow it immediately with|safeFilter, explicitly tells the template engine: this content is safe and does not need to be HTML-escaped. Therefore, when usingurlize, you will usually see{{ 变量 | urlize | safe }}such combinations.

How to use in templateurlizeFilter?

urlizeFilters have two main uses that can meet your needs at different locations in the template:

1. Inline transformation of a single variable

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

Example Usage:

Assume you have an article objectitemwhere,item.DescriptionThe field may contain some URLs.

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

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

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

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

Hereurlize:trueRepresents escaping the display text of the link itself.

2. Batch convert content of tag blocks

When you want to perform URL encoding on a larger area of the template, which includes multiple lines of text, even a mix of static text and dynamic variables, you can use{% filter urlize %}Tag block. This tag block will treat all the text content inside it as a whole and apply it uniformlyurlizeFilter. This is the key to implementing URL conversion at any location in the AnQiCMS template.

Example Usage:

Suppose 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 %}Block content, whether you write static text or through{{ }}the output variables, any string that conforms to the URL or email format 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 appearance of the page. AnQiCMS providesurlizetruncFilter, its function is withurlizeSimilar, but allows you to specify a length, if the display text of the link exceeds this length, it will be truncated with...indicating an omission.

Example Usage:

<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, each converted link's display text (not the actualhref) 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 fields. 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 profile descriptions, and other user-generated content, useurlizeCan greatly enhance its usability. However, be cautious when dealing with user-generated content.|safebecause it bypasses the default HTML escaping. Althoughurlizewill generatenofollowAttributes, but also ensure the overall output safety when used before or after other filters.
  • A concise display on the list page:In the brief descriptions of article lists and product lists, if there is a URL, it can be made clickable to improve the efficiency of information acquisition.urlizeQuickly make it clickable 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:

  • |safeNot to be omitted:[en]Again, I emphasize,urlizeThe generated is an HTML tag, if not配合|safeThese tags will be output as plain text, links will not work.
  • Avoid repeating HTML:If your content is already structured HTML (for example, from a rich text editor), do not apply it again:urlizeMay result in unexpected outcomes, even destroying the original structure. UsuallyurlizeSuitable for plain text content.
  • nofollowProperties:AnQiCMS automatically adds forurlizelinks generatedrel="nofollow"This is a good practice for handling external links, which helps maintain the SEO performance of the website.

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

Common Questions (FAQ)

1.|safeWhat is the purpose of the filter, and when is it a must-use?

|safeThe filter tells AnQiCMS's template engine that the HTML code output by the variables or tags before it is safe and does not require default HTML escaping. It isMustBe used after any filter that outputs HTML tags (such asurlize/linebreaksAnd so on) so that these HTML tags can be normally parsed and rendered by the browser. For example,urlizethe filter willwww.example.comConvert to `href=“http”