In the Anqi CMS backend custom field, if a field stores a URL, how can you use the `stringformat` filter to validate its format in the template?

Calendar 👁️ 72

Storing URLs in the AnQiCMS backend custom fields is a very practical feature that allows us to add various personalized information to content models according to business needs.However, when these URLs need to be displayed in the front-end template, we must not only ensure that they can be output correctly, but also sometimes hope to perform some basic format checks to enhance the robustness and user experience of the page.This article will discuss how to cleverly utilize in AnQiCMS templatestringformatThe filter combines other functions to process and discuss the preliminary 'verification' of URLs stored in custom fields.

AnQiCMS custom field: the foundation for storing URLs

AnQiCMS provides flexible content model features, allowing users to customize fields according to actual needs, such as text, numbers, images, etc.When we need to store external links, download addresses, or social media homepages and other URLs, we usually choose the 'single-line text' type of custom field.For example, create a named in the "Article Model" named外部资源链接Custom field, its "call field" is set toexternal_linkUsed to store external URLs related to articles.

When editing content in the background, the user will enter the full URL (such ashttps://www.example.com/resourceFill in this custom field. Once the data is saved, we can retrieve the values of these custom fields through specific tags in the frontend template.Generally, custom fields for document detail pages are used toarchiveDetailTags:

{% archiveDetail externalLinkValue with name="external_link" %}

here,externalLinkValuewhich is the URL string we get from the custom field "external_link".

UnderstandingstringformatFilter

stringformatIs provided by the AnQiCMS template engine, a powerful and general-purpose filter, whose main function is to convert various data types (whether they are numbers, strings, or more complex objects) into standard string formats according to our preset formats for output. Its usage is similar to that in Go language.fmt.Sprintf()Function.

For example, if we want to ensure that a variablemyVarregardless of its original type, we can output it as a plain string by usingstringformatof%sthe format symbol:

{{ myVar|stringformat:"%s" }}

AlthoughstringformatIt is mainly used for formatting output, but it ensures that we get a pure string first when handling custom URL fields, laying the foundation for subsequent checks and displays.

Display in template and preliminary "verification" URL

The basic requirement is to display the URL stored in the custom field in the template, but if the URL format is incorrect, it may cause the link to fail or the page to display an error. Althoughstringformatdoes not have strict URL syntax validation capabilities (such as judgmenthtttp://Whether it is a legal protocol), but we can achieve a lightweight, template-level preliminary 'verification' by combining other filters and logical judgment tags in the AnQiCMS template.

This verification mainly refers to checking if the URL contains common protocol prefixes such ashttp://orhttps://), and ensure it is not a null value. If it passes these basic checks, we will then render it as a clickable hyperlink.

To achieve this, we can take the following steps:

  1. Get custom field value: As mentioned above, usearchiveDetailtags to obtain the stored URL.
  2. Cleaning and preliminary inspection: Use.trimThe filter removes any leading and trailing whitespace from the URL string and then useslengthThe filter checks its length as well ascontainThe filter checks if it contains a protocol header.
  3. Formatted output and conversionUtilizestringformatMake sure the output is combined into a stringurlizeThe filter converts the string into a clickable hyperlink.urlizeThe filter itself has certain intelligent recognition capabilities, able to automatically convert URLs and email addresses in text to<a>tags and add them by defaultrel="nofollow"Properties, which are beneficial for SEO and user experience.

Practical case: Display URLs safely and beautifully.

Suppose we have a custom field, the field name is called.my_custom_url_fieldUsed to store the reference link of the article. We hope to display it as a clickable link on the article detail page if this field has a value and looks like a valid URL, otherwise display the corresponding prompt.

”`twig {# 1. From the custom field to get the URL value #} {% archiveDetail customUrlField with name=“my_custom_url_field” %}

{% if customUrlField is not empty %} {# Check if the field is empty #}

{# 2. 清理URL字符串,去除首尾空白字符 #}
{% set cleanUrl = customUrlField|trim %}

{# 3. 进行初步“验证”:检查长度并判断是否包含常见的协议头 #}
{% if cleanUrl|length > 7 and (cleanUrl|contain:"http://" or cleanUrl|contain:"https://") %}
    <p>
        外部资源链接:
        {# 4. 使用stringformat确保输出为字符串,再通过urlize转换为可点击链接 #}
        {{ cleanUrl|stringformat:"%s"|urlize|safe }}
    </p>
{% else %}
    {# 如果初步验证不通过,提供提示 #}
    <p>外部资源链接:提供的地址 (<code>{{ cleanUrl }}</code>) 格式不符合URL规范,请检查。</p>
{% endif %}

{% else %}

{# 如果自定义字段本身就没有值,也提供提示 #}
<p>外部资源链接:暂无。</p>

{% endif %}

Related articles

Can the `stringformat` filter convert a Go language slice or Map into a readable JSON string output?

When developing templates for AnQiCMS, we often encounter such questions: The background data is a slice (Slice) or map (Map) structure in Go language, and if we want to output these data in a readable JSON string format in the front-end template, can the `stringformat` filter built into AnQiCMS handle it?This is indeed a very practical requirement, after all, JSON format is ubiquitous in modern web development.

2025-11-08

How to safely handle user input that may contain JS code in the comment or message form of Anqi CMS using the `escapejs` filter?

In website operation, the comment area and message board are important channels for interacting with users and collecting feedback.However, this area where users can freely enter content is often an entry point for potential security risks, especially cross-site scripting (XSS) attacks.As website administrators, we must ensure that the content entered by users is safe when displayed on the frontend and is not exploited maliciously.The Anqi CMS, a system focused on providing secure and efficient content management solutions, has provided us with powerful tools to meet such challenges. Today

2025-11-08

How does the `stringformat` filter handle null or invalid input in AnQi CMS, will it return an error or a default value?

In Anqi CMS template design, we often encounter scenarios where we need to format variable output.At this point, the `stringformat` filter is particularly important, as it helps us clearly display numbers, strings, and even other types of data according to the format we preset.However, when using such tools, a common and crucial question is: how will `stringformat` handle it when the variable itself is null or invalid?Is it a direct error that causes the page to crash, or is there a more elegant default behavior?

2025-11-08

How to use the `stringformat` filter in Anqi CMS template to format price numbers as currency (such as “¥%.2f”)?

When displaying product or service prices on a website, we all hope that they look clear and professional, easy to understand.A sequence of price numbers without currency symbols and inconsistent decimal places, which not only affects the appearance but may also raise doubts about the professionalism of the product. 幸运的是,AnQiCMS(AnQiCMS)强大的模板引擎提供了多种实用的过滤器,其中 `stringformat` 过滤器就是将数字格式化为标准货币形式的利器。

2025-11-08

Does the `stringformat` filter support custom internationalization format output for datetime objects?

In the daily operation of the website, we often need to display date and time information in a user-friendly manner.Especially when facing users from different regions, it is particularly important to be able to output date and time formats that conform to local customs, which is what we commonly refer to as 'internationalized format output'.Today, let's talk about a commonly used filter `stringformat` in AnQiCMS, and see if it supports this customized internationalized format output for date and time objects.

2025-11-08

How to use the `stringformat` filter to generate a numeric string with leading zeros or a specific width in AnQi CMS (such as order numbers)?

In website operation, we often need to handle various number strings with specific formats, such as order numbers, product codes, or member IDs.These numbers usually need to maintain a certain length, and leading zeros are used to fill in when the numbers are insufficient to ensure uniformity and aesthetics.AnQiCMS (AnQiCMS) provides a very practical template filter——`stringformat`, which can help us easily meet these needs.

2025-11-08

In AnQi CMS template, how to automatically get the thumbnail version of a dynamically generated image URL (such as `{{item.Logo}}`) through the `thumb` filter?

In website content operation, images are an indispensable element to enhance user experience and convey information.However, how to ensure the quality of images while also considering the loading speed and layout beauty of the website, especially in the case of a large number of images with dynamic sources, has become a challenge for many operators.AnQiCMS as an efficient and flexible content management system provides us with an elegant solution, including the `thumb` filter for handling dynamic image URLs and automatically retrieving thumbnails.Why do we need thumbnails? We all know

2025-11-08

Does the `thumb` filter in AnQi CMS support specifying the width and height of the thumbnail, or only fetching the cropped URL?

When using Anqi CMS for website content management, we often need to handle images, especially thumbnails for articles or products.This is when the `thumb` filter comes into play.It can help us easily generate and obtain the thumbnail address from a complete image address.However, many friends may be curious, does this `thumb` filter support specifying the width and height of thumbnails directly when used?Or is it just returning a cropped image URL?

2025-11-08