How to safely concatenate string and numeric variables in the AnQiCMS template?

Calendar 👁️ 69

During the development of AnQiCMS templates, we often need to combine different text fragments, numerical information, and even system variables to form a complete output content, such as building dynamic links, displaying formatted data, or generating user-friendly prompt information.This process involves concatenating string and numeric variables, and how to safely and efficiently complete this operation is a crucial aspect of template development.AnQiCMS's powerful template engine provides a variety of flexible mechanisms to support these needs.

AnQiCMS's template engine syntax is similar to Django, variable output is done using double curly braces{{ 变量名 }}And control logic such as conditional judgment and loop is done using single curly braces and percent signs{% 标签 %}. Understanding this basic syntax is the first step in efficient template development.

Basic variable output and automatic escaping in templates.

In AnQiCMS templates, when we use{{ 变量名 }}When outputting variables, the system defaults to executing "auto-escaping". This means that special characters such as HTML tags and JavaScript code are converted to safe entity characters, for example<Will become&lt;,>Will become&gt;. This mechanism is a built-in security measure of the AnQiCMS template engine, designed to effectively prevent cross-site scripting attacks (XSS), ensuring that your website content is not damaged by maliciously injected code when displayed.

Therefore, unless you have a clear reason and are 100% sure of the security of the content, it is usually not necessary to perform additional manual escaping operations.In most cases, output the variable directly.

Safely concatenate strings and numbers

AnQiCMS provides multiple ways to concatenate strings and numbers, let's understand one by one.

1. UseaddFilter for simple concatenation

The most direct and commonly used method of concatenation is to utilizeaddThe filter is very intelligent and can handle various types of variables, whether it is adding strings with strings, numbers with strings, or numbers with numbers, it will try to convert and concatenate reasonably.

Usage: {{ 变量1|add:变量2 }}

Example:Suppose we have an article IDarchive.IdIt is a number100, the article titlearchive.TitleIt is a string"AnQiCMS模板教程".

  • Concatenating a string with a number:If we want to display "Article ID: 100", we can write it like this:

    {{ "文章ID: "|add:archive.Id }}
    {# 输出: 文章ID: 100 #}
    

    Here, the filter will automatically convert numbers100Concatenate the string with the preceding text.

  • Concatenate strings:If you need to concatenate two strings, for example, to combine a filename:

    {{ "header"|add:".html" }}
    {# 输出: header.html #}
    
  • Add numbers:Of course,addThe filter also supports pure numeric addition operations, for example, calculating the total:

    {% set price = 50 %}
    {% set quantity = 2 %}
    {{ price|add:quantity }}
    {# 输出: 52 #}
    

addThe filter will ignore the content that cannot be added together during automatic conversion, which increases its fault tolerance, but it also means that we need to ensure that the variables being concatenated meet expectations.

2. UsestringformatFilter for refined format output

When you need more complex format control, such as inserting multiple variables in a text, or formatting numbers in a specific way (such as retaining decimal places),stringformatThe filter is your powerful assistant. It is similar toprintforsprintfFunction.

Usage: {{ "格式字符串"|stringformat:变量1, 变量2, ... }}

placeholder in format strings:

  • %s: string placeholder
  • %d: integer placeholder
  • %.2f: floating-point placeholder (.2round to two decimal places
  • %v: Default format output, usually used for complex types or uncertain types

Example:Assuming we havearchive.TitleWith"AnQiCMS模板指南",archive.ViewsWith1234,archive.PriceWith99.95.

  • Combine multiple variable text:

    {{ "文章标题:%s,浏览量:%d 次。"|stringformat:archive.Title, archive.Views }}
    {# 输出: 文章标题:AnQiCMS模板指南,浏览量:1234 次。 #}
    
  • Format numeric output:If we want to format the price to two decimal places:

    {{ "商品价格:%.2f 元"|stringformat:archive.Price }}
    {# 输出: 商品价格:99.95 元 #}
    
  • Mixed with multiple formats:

    {{ "商品名称:%s,价格:%.2f 元,已售出:%d 件"|stringformat:archive.Title, archive.Price, archive.Views }}
    {# 输出: 商品名称:AnQiCMS模板指南,价格:99.95 元,已售出:1234 件 #}
    

    stringformatProvides powerful output control capabilities, making your data display more standardized and beautiful.

3. Pay attention to the handling of numeric variables

Although the AnQiCMS template engine can intelligently handle variable types most of the time, it is a good habit to explicitly perform type conversion before performing complex numerical calculations, especially when the variables come from user input or external data sources and the type may be uncertain.

  • Direct arithmetic operations:In{{ }}In this case, you can perform basic arithmetic operations on numeric variables:

    {% set num1 = 10 %}
    {% set num2 = 5 %}
    {{ num1 + num2 }} {# 加法 #}
    {{ num1 - num2 }} {# 减法 #}
    {{ num1 * num2 }} {# 乘法 #}
    {{ num1 / num2 }} {# 除法 #}
    {# 输出: 15, 5, 50, 2 #}
    

    Here, ifnum1ornum2Can be converted to a numeric string (for example"10"), template engines usually handle them correctly.

  • Explicit type conversion:integerandfloatFilter:If a variable may be a string representation of a number but you need to ensure it is a numeric type before the operation, you can useintegerorfloatFilter:

    {% set str_num = "123" %}
    {{ str_num|integer|add:45 }}
    {# 输出: 168 #}
    
    {% set str_price = "99.99" %}
    {{ str_price|float|stringformat:"%.1f" }}
    {# 输出: 99.9 #}
    

    These filters will return when the conversion fails0or0.0Therefore, error handling needs to be considered in practical applications.

  • Timestamp to date string conversion:stampToDateTags:The timestamp in AnQiCMS is usually of numeric type. To convert it to a readable date string, you can usestampToDateTags:

    {{ stampToDate(archive.CreatedTime, "2006-01-02 15:04") }}
    {# 将10位时间戳格式化为 "年-月-日 时:分" 格式 #}
    

    Here"2006-01-02 15:04"It is the Go language-specific date formatting base time, representing2006年1月2日15点04分Define the date format of the output through it.

Security considerations in practice

Again, the automatic escaping function of AnQiCMS template is your security guarantee.

  • Default security: Just in case you use `{{

Related articles

How to randomly get a character or value from a string or array?

In Anqi CMS template design, we often encounter the need to dynamically display content, such as randomly recommended articles, randomly displayed product images, or randomly selecting one from a set of preset keywords for display.To achieve this flexible and varied content presentation, Anqi CMS provides simple and powerful template filters, including the `random` filter that can randomly select a character or value from a string or array.Understand and master the `random` filter, which can make our website content more vibrant and fresh, effectively enhancing the user experience

2025-11-08

How to configure multi-site content display in AnQiCMS

Easily implement multi-site content management and display in AnQiCMS It is a challenge for users who operate multiple brands, sub-sites, or content branches to manage the content of each site uniformly.AnQiCMS provides powerful multi-site management features, allowing you to easily create and maintain multiple independent websites under a single system instance and flexibly control the display of their content.This article will give a detailed introduction on how to configure multiple sites in AnQiCMS and achieve independent management and display of content.### 1. Prepare the work

2025-11-08

In document management, how is the recommended attribute `flag` used to control the display of content on the homepage or other special locations?

In Anqi CMS, the "recommended attribute" (`flag`) is a powerful and flexible feature that allows you to finely control the display of website content on the homepage, category pages, or other specific display areas.Understanding and effectively using this attribute can significantly improve the content operation efficiency and user experience of your website.What is the "recommended attribute" (`flag`) in Anqi CMS?In the Anqi CMS document management module, when you add or edit a document, you will find an option named "recommended properties".These attributes are not traditional classifications or tags

2025-11-08

How to configure independent SEO information and template display for a single page (such as "About Us") in the page management?

In website operation, each page has its unique value and goal.For pages such as "About Us", "Contact Us", and "Terms of Service", they often carry brand stories, core values, or important contact information, which are crucial for building corporate image and user trust.Therefore, configuring exclusive SEO information and personalized display templates for these specific pages is an effective way to enhance the professionalism and user experience of the website.AnQiCMS deeply understands these needs, providing flexible and powerful functions, allowing you to independently configure SEO information and specify personalized template display for each single page

2025-11-08

How to correctly escape special characters in the AnQiCMS template to avoid display errors?

In website content management, we often need to display text containing various special characters.If these special characters are not handled correctly, it may lead to page layout chaos, functional anomalies, and even security vulnerabilities.AnQiCMS provides a powerful mechanism to help us handle these special characters during template rendering, ensuring the correct display of content and the security of the website.

2025-11-08

How to automatically capitalize the first letter of an article title, or to achieve full uppercase/lowercase conversion?

In content operation, a standardized and unified title format is crucial for the brand image of the website and the user reading experience.To enhance visual tidiness or to meet specific design styles, automatically adjusting the case of the article title is a very practical feature.AnQiCMS as a flexible content management system, provides a convenient way to help us achieve this goal without complex programming, and it can be easily handled.

2025-11-08

How to achieve text centering or left-right alignment formatting in templates for AnQiCMS?

In web design, the layout and alignment of content are key elements of user experience.No matter if you want to center the title or align the paragraph text to the left, AnQiCMS provides a flexible template mechanism, combined with standard Web technology, which can easily meet these needs.AnQiCMS as a content management system developed based on the Go language has its core advantages in providing efficient, customizable content management and data output.It uses a syntax similar to the Django template engine, allowing you to combine system data (such as article titles, content, etc.) with

2025-11-08

How to determine if a string or array in the AnQiCMS template contains a specific keyword?

In Anqi CMS template development and daily content operation, we often encounter the need to dynamically display information based on specific attributes or keywords of the content.To achieve personalized content recommendation, emphasize the specific theme of an article, or control the display of page elements based on certain indicators in the data, accurately determining whether a string or array contains specific keywords is a very practical skill.The Anqi CMS template system adopts a syntax similar to the Django template engine, built-in with rich filters and tags, which can help us easily implement such judgments. Next

2025-11-08