In the template design of AnQi CMS, handling and displaying data flexibly is the key to building a dynamic website.This is a common requirement in daily development to concatenate numbers or strings.The Anqi CMS provides various ways to achieve this goal, from simple direct combinations to powerful filters, all of which can meet your different content concatenation scenarios.
Understanding the basics of concatenation: direct output and 'addition'
In the template syntax of AnQi CMS, the most intuitive way to concatenate strings is to place multiple variables or text directly next to each other. For example, if you want to combine the article title and the site name in the webpage title, you can write it directly as<h1>{{ archive.Title }} - {{ system.SiteName }}</h1>The template engine will convert their respective values to strings and concatenate 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 providedaddThe filter is very convenient.addThe filter can not only concatenate strings but also perform numeric addition if possible.
addThe flexible use of the filter
addThe filter is a powerful tool for handling number concatenation. Its basic syntax is{{ obj|add:obj2 }}where,objis the first value you want to operate on,obj2is the second value you want to add.
Adding numbers: when
objandobj2when both are numbers,addThe filter performs mathematical addition. For example:{{ 5|add:2 }} {# 结果:7 #} {{ 10|add:40 }} {# 结果:50 #}This is very useful when dynamic calculations and the display of a total or statistics are needed.
String concatenation: when
objorobj2(or both) are strings when,addThe filter will concatenate them. For example:{{ "安企"|add:"CMS" }} {# 结果:安企CMS #}Mixing numbers with string concatenation:
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.{{ 5|add:"CMS" }} {# 结果:5CMS #} {{ "安企"|add:2 }} {# 结果:安企2 #}This flexibility means you do not have to manually perform type conversion, thus simplifying template code.
Translate empty values or non-numerical valuesIf
obj2Yesnothing(Empty value) or cannot be converted to number/string,addThe filter will return based on the specific situation, possibly onlyobjthe value, or ignore the parts that cannot be added. For example:{{ 5|add:nothing }} {# 结果:5 #}
PassaddFilter, you can easily generate dynamic text, such as building descriptions with product quantities or status information.
Combination of array content:joinFilter
In some scenarios, you may need to combine all elements of an array or list into a single string, separated by a specific delimiter. At this time,joina filter is used to **select.
joinThe syntax of the filter is{{ array|join:"分隔符" }}.
For example, if you have an array of 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 arraytagsEach element's title (or its default string representation) is connected by commas and spaces to form a complete string.
Fine-grained output control:stringformatFilter
For scenarios that require more advanced formatting and combination, such as inserting variables into strings and aligning numbers, controlling floating-point precision, etc.,stringformatThe filter provides functionality similar to the Go languagefmt.Sprintf()的功能【en】:.
Its syntax is【en】:.{{ obj|stringformat:"格式定义" }}。For example, if you want to format a number into a string with a prefix:【en】:.
{{ archive.Id|stringformat:"文章ID-%d" }} {# 结果:文章ID-123 #}
or combine it with other strings for formatting:【en】:.
{{ system.SiteName|stringformat:"欢迎来到 %s 的网站!" }} {# 结果:欢迎来到 安企CMS 的网站! #}
stringformatThe filter provides rich formatting options (such as)%sfor strings,%dfor integers,%.2fUsed for floating-point numbers and retaining two decimal places, etc.), allowing you to precisely control the structure and content of the output string.
Things to note when concatenating
- HTML content concatenation and securityIf the string you concatenate may contain HTML code (for example, from user input rich text content), please make sure to use
safeFilter, such as{{ content|safe }}[en] Otherwise, the template engine will default to HTML escaping, displaying HTML tags as plain text to prevent XSS attacks. - [en] Code readabilityAlthough it is possible to concatenate multiple variables and strings directly, when the concatenation logic becomes complex,
addFilter orstringformatit can improve the readability and maintainability of the code. - debuggingIf the concatenation result is not as expected, you can use
dumpfilters (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 the Anqi CMS template more vivid and accurate, better meeting the operational needs of the website.
Common Questions (FAQ)
Q: Can I use
addDoes the filter perform pure numeric addition operations? Answer:Yes, 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 attempt to convert both of them to strings and then concatenate them.How to add a fixed separator, such as a space or a hyphen, between each part when concatenating strings? AnswerFor concatenating a few strings, you can directly insert the delimiter as a literal, for example
{{ var1 }} - {{ var2 }}. If you need to concatenate multiple elements from an array, separated by a delimiterjoinFilter is a better choice, for example{{ tags|join:", " }}.Question: If the string I need to concatenate contains many variables and fixed text, and I need to control the format precisely, which method should I use? AnswerIn this case,
stringformatthe filter will be your best choice. It provides powerful formatting capabilities, allowing you to use it as if you were using the Go language'sfmt.Sprintf()Define the output template in such a way that it precisely controls the insertion position and format of each variable, for example,{{ "%s 的产品数量是 %d 个"|stringformat:productName, productCount }}.