How to perform simple number or string concatenation in AnqiCMS template?

Calendar 👁️ 72

In AnQi CMS template design, flexibly handling and displaying data is the key to building a dynamic website.This is a common need in daily development to concatenate numbers or strings.AnQi CMS provides various ways to achieve this goal, from simple direct combinations to powerful filters, which can meet your different content assembly scenarios.

Understanding the basics of concatenation: Direct output and 'plus'

In AnQi CMS template syntax, the most direct way to concatenate strings is to place multiple variables or text side by side. For example, if you want to combine the article title and site name in the webpage title, you can directly write it as<h1>{{ archive.Title }} - {{ system.SiteName }}</h1>. The template engine will convert their respective values to strings and combine them in order.

However, when you need to perform more complex "concatenation" operations, especially involving numerical calculations or intelligent handling of different data types, the Anqi CMS providesaddthe filter becomes very convenient.addThe filter can not only concatenate strings but also perform numeric addition when possible.

addThe flexible application of the filter.

addThe filter is a powerful tool for handling number and string concatenation. Its basic syntax is{{ obj|add:obj2 }}of whichobjis the first value you will operate on,obj2is the second value you will add.

  1. Adding numbers:Whenobjandobj2when both are numbers,addthe filter will perform mathematical addition.

    {{ 5|add:2 }}  {# 结果:7 #}
    {{ 10|add:40 }} {# 结果:50 #}
    

    This is very useful when it is necessary to dynamically calculate and display the total and statistical information.

  2. String concatenation:Whenobjorobj2When both (or either) are strings,addThe filter will connect them together. For example:

    {{ "安企"|add:"CMS" }} {# 结果:安企CMS #}
    
  3. Mixing numbers and strings:addThe filter can intelligently handle the mixed concatenation of numbers and strings.If one is a number and the other is a string, it usually converts the number to a string before concatenating. For example:

    {{ 5|add:"CMS" }}   {# 结果:5CMS #}
    {{ "安企"|add:2 }} {# 结果:安企2 #}
    

    This flexibility means you don't have to manually perform type conversion, thus simplifying template code.

  4. Handling null or non-numeric valuesIf:obj2Isnothing(empty value) or cannot be converted to a number/string,addThe filter may return only based on the specific situation,objor ignore the parts that cannot be added. For example:

    {{ 5|add:nothing }} {# 结果:5 #}
    

ByaddFilter, you can easily implement dynamic text generation, such as building descriptions with product quantity or status information.

Combination of array content: joinFilter

In some cases, you may need to combine all elements of an array or list into a single string, separated by a specific delimiter. At this point,joinThe filter is **selection.

joinThe syntax of the filter is{{ array|join:"分隔符" }}. For example, if you have an array storing article tagstags, you can display it as a comma-separated string:

{% tagList tags with itemId=archive.Id limit="10" %}
    <p>文章标签:{{ tags|join:", " }}</p>
{% endtagList %}

This will convert the arraytagsConnect the titles (or their default string representation) of each element with commas and spaces to form a complete string.

Fine-grained output control:stringformatFilter

For more advanced formatting and combination scenarios, such as inserting variables into strings and aligning numbers, controlling floating-point precision, etc.,stringformatThe filter provides functionality similar to Go languagefmt.Sprintf()function.

The syntax is{{ obj|stringformat:"格式定义" }}. For example, you want to format a number into a string with a prefix:

{{ archive.Id|stringformat:"文章ID-%d" }} {# 结果:文章ID-123 #}

Or combine it with other strings for formatting:

{{ system.SiteName|stringformat:"欢迎来到 %s 的网站!" }} {# 结果:欢迎来到 安企CMS 的网站! #}

stringformatThe filter provides a rich set of formatting options (such as%sUsed for strings,%dUsed for integers,%.2fUsed for floating-point numbers and retaining two decimal places, etc.), allowing you to accurately control the structure and content of the output string.

Attention points when concatenating

  • HTML content concatenation and safety: If the concatenated string may contain HTML code (for example, from user input rich text content), be sure to usesafea filter such as{{ content|safe }} Otherwise, the template engine will default to HTML escaping, displaying HTML tags as plain text to prevent XSS attacks.
  • Code readability: You can concatenate multiple variables and strings directly, but when the concatenation logic becomes complex, usingaddOr filter.stringformatcan improve the readability and maintainability of the code.
  • DebugIf the concatenation result is not as expected, you can usedumpFilter (such as{{ myVariable|dump }}) to view the actual type and value of the variable, which is very helpful for debugging.

By flexibly using these concatenation techniques, you can make the content display of Anqi CMS template more vivid and accurate, better meeting the operation needs of the website.


Frequently Asked Questions (FAQ)

  1. Can I useaddDoes the filter perform pure numerical addition operations? AnswerYes, whenaddBoth operands of the filter are numbers (integers or floating-point numbers), it will perform mathematical addition. For example{{ 10|add:5 }}You will get15If one of the operands is not a number, it will try to convert both of them to strings and then concatenate them.

  2. How to concatenate strings while adding a fixed separator between each part, such as a space or a hyphen? AnswerFor concatenating a few strings, you can directly insert the separator as a literal, for example{{ var1 }} - {{ var2 }}If you need to concatenate multiple elements of an array, separated by a separator,joinThe filter is a better choice, for example{{ tags|join:", " }}.

  3. Question: If I need to concatenate a string that contains many variables and fixed text, and need to control the format accurately, which method should I use? AnswerIn this case,stringformatThe filter will be your best choice. It provides powerful formatting capabilities, allowing you to use Go language as if you were usingfmt.Sprintf()Such an output template is defined, precise control of the insertion position and format of each variable, for example{{ "%s 的产品数量是 %d 个"|stringformat:productName, productCount }}.

Related articles

How to remove leading and trailing spaces or specified characters from a string?

In website content management, string formatting is often a problem we need to solve when displaying content and handling data.Especially in user input, data import, or system-generated content, strings may have extraneous spaces at the beginning and end, or specific characters may need to be removed to meet expected display effects or data standards.AnQiCMS as an efficient and flexible content management system, through its powerful template engine and rich filters, provides us with concise and powerful string processing capabilities, allowing such tasks to be easily completed at the template level.

2025-11-08

How to format numbers in Anqi CMS (such as retaining decimal places for floating-point numbers)?

In website operation, the way data is displayed is crucial to user experience.Whether it is product prices, statistics, or financial statements, clear and standardized number formats can not only enhance the professionalism of the website but also help users understand information more intuitively.AnQi CMS knows this need, and provides powerful number formatting functions in the template system, allowing us to easily control the decimal places of floating-point numbers, the display style of integers, and more customized presentations of numbers.### Why is Number Formatting So Important? Imagine a e-commerce website where the price of a product is displayed as "199"

2025-11-08

How to automatically convert a URL string to a clickable link in a template?

In website content operation, we often encounter such situations: articles, introductions, or comments contain some URL strings that can be seen by users but cannot be directly clicked to jump, which not only affects user experience but also reduces the readability and practicality of the content.As an AnQiCMS user, you will find that the system provides us with a set of elegant and efficient solutions that can easily convert these ordinary URL strings into clickable links.AnQiCMS's template engine is powerful and flexible, it draws on the concise syntax of Django templates

2025-11-08

How to convert newline characters in multi-line text to HTML tags in AnqiCMS?

In website content operation, we often need to input multi-line text in articles, product descriptions, or page content.However, when displaying text with line breaks directly on a web page, browsers often do not retain these line breaks as expected, instead rendering them as a single continuous line of text, which undoubtedly affects the reading experience and layout of the content.AnQi CMS understands this and provides very convenient built-in functions to help us easily convert newline characters in multi-line text to corresponding HTML tags, allowing the content to be perfectly presented on the front-end page.###

2025-11-08

How to convert an array to a string with a delimiter, or split a string into an array?

In AnQi CMS template development, we often encounter situations where we need to handle data format conversion, especially when combining multiple values into a string or splitting a string containing multiple values into independent data.This is especially common when dealing with tags, multi-select properties, or extracting information from custom fields. 幸运的是,AnQi CMS built-in very practical template filters, can help us easily achieve the conversion between arrays and string with delimiters.

2025-11-08

How to determine if a string or array contains specific content in AnqiCMS?

In the daily work of content operation, we often need to make judgments and displays based on specific information of the content.For example, if a blog post mentions a hot keyword, we may want to give it a special tag; or if a product description includes a certain feature, we want to adjust its display style accordingly.The template engine of AnQiCMS provides a flexible and intuitive way to determine whether a string or array contains specific content, making dynamic content display and personalized processing very convenient.

2025-11-08

How to debug and view the complete structure and value of variables in the template?

When developing website templates in AnQi CMS, we often need to understand the specific structure of a variable on the page and what data it contains so that we can accurately call its properties.When dealing with complex business logic or unfamiliar template variables, being able to quickly view the complete structure and value of variables is undoubtedly the key to improving development efficiency.The Anqi CMS based on the Django template engine provides a concise and powerful variable debugging method for us.### Core Tool: `dump` Filter An enterprise CMS template provides a `dump` named

2025-11-08

How to display the comment form and submit comments in Anqi CMS?

It is crucial to establish an effective communication channel with visitors in website operation, and the message function is one of the key tools to achieve this goal.It can not only help websites collect user feedback and answer questions, but also promote user participation, enhance the interactivity and stickiness of the website.For users using AnQiCMS, the built-in message function provides a convenient and flexible solution, allowing you to easily display and submit message forms without writing complex code.### Overview of AnQi CMS Message Function The AnQi CMS message function is designed to be very user-friendly

2025-11-08