In AnQiCMS template development, we often encounter scenarios where it is necessary to display numeric data combined with text content.For example, you may need to add the product ID at the end of a product title, or add "times read" after the number of reads in an article.When dealing with such requirements, a common question is: how to flexibly convert numeric fields in templates to strings and concatenate them without affecting other logical judgments or calculations?
Luckyly, AnQiCMS's powerful Django-like template engine (Pongo2) provides us with a variety of concise and effective methods to solve this problem, whether it is implicit conversion or explicit control, it can be easily handled.
The most direct way: implicit conversion
In AnQiCMS templates, most of the time you don't even need special operations.When you place a numeric variable directly next to a string literal or use it as part of a label output, the template engine usually automatically converts the number to a string for output.
For example, if you have an ID field in an article object (assumingarchive.Idit is a number), and you want to display it in a link:
<a href="/article/{{ archive.Id }}">查看文章详情</a>
Or, would you like to display the number of times the article has been read:
<p>这篇文章已被阅读 {{ archive.Views }} 次。</p>
In these two examples,archive.Idandarchive.ViewsAlthough it is of numeric type, the template engine will automatically convert it to a string and then concatenate it with the surrounding text, thereby displaying the complete text you expect on the page.This method is simple and direct, suitable for most scenarios where only numeric content needs to be displayed.
Flexible combination:addFilter
When you need to explicitly combine numbers with strings or other numbers, or in some complex scenarios that require variable concatenation,addA filter is a very practical tool.addThe filter can be used to add two values together. If both values are numbers, it will perform mathematical addition;If at least one of the values is a string, it will convert the number to a string and then perform the string concatenation operation.
This means, you can use it to concatenate a numeric variable with another string variable, not just with literals:
{% set views_count = archive.Views %} {# views_count 是一个数字 #}
{% set views_suffix = "次观看" %} {# views_suffix 是一个字符串 #}
<p>视频播放量:{{ views_count|add:views_suffix }}</p>
In this example, evenviews_countis a number,addThe filter will also intelligently convert it to a string, then concatenate it withviews_suffixto generate a result like “12345 views” (assumingarchive.ViewsThis is 12345). This approach provides great flexibility when you need to dynamically combine strings and numbers from different sources.
Fine control:stringformatFilter
If simple conversion and concatenation are not enough, you may need to control the display format of numbers more finely, such as retaining a specific number of decimal places, padding leading zeros, or displaying in currency format. At this time,stringformatThe filter comes into play.
stringformatThe filter allows you to use Go language'sfmt.Sprintf()The style of formatted string, which converts any value (including numbers) into a string with a specific format.It still produces a string, so it can be seamlessly concatenated with any other string.
For example, if you want to format a floating-point number to two decimal places and display it as currency:
{% set product_price = 99.95 %}
<p>商品价格:{{ product_price|stringformat:"¥%.2f" }}</p> {# 输出: ¥99.95 #}
For example, you have a numeric ID, but you want it to always be 4 digits, and if it is less than 4 digits, it is filled with zeros in front:
{% set item_id = 7 %}
<p>商品编号:{{ item_id|stringformat:"商品ID:%04d" }}</p> {# 输出: 商品ID:0007 #}
BystringformatYou can fully control the appearance of numbers when converted to strings, ensuring it meets the strict requirements of page design while also being convenient for concatenation with other string content.
Summary
In AnQiCMS templates, it's not difficult to convert numeric fields to strings and concatenate them. For most simple display needs, the template engine'simplicit conversionThe functionality is sufficient. When you need to dynamically combine a numeric variable with a string variable,addFilterit provides convenient concatenation capabilities. And when you need to precisely control the display format of numbers,stringformatFilterIt is the preferred method to achieve this goal.
These methods only affect the "presentation" of data in the template and do not change the original data type of the variables, so you can safely perform various logical judgments and calculations in the template without worrying about the side effects of type conversion.Choose the method that best suits your current needs, making your template code clearer and more efficient.
Frequently Asked Questions (FAQ)
1. How to perform mathematical operations on numbers before string concatenation?
You can use arithmetic operation tags (such as{% calc %}or consecutiveaddFilter) for numerical calculations. For example, if you need to add two numbers first and then concatenate with a string:
{% set num1 = 10 %}
{% set num2 = 20 %}
{% set result = num1|add:num2 %} {# result 现在是数字 30 #}
<p>总和是:{{ result|add:"个" }}</p> {# 输出: 总和是:30个 #}
2. Will converting a number to a string affect its subsequent numerical calculation in the template?
I won't. AnQiCMS template filters mainly handle the 'display' logic of variables in templates. When you useaddorstringformatFilters convert numbers to strings for concatenation, which is just a "formatted output" at the current output stage. The original number variables still maintain their numeric type in the template context, and in subsequent logic judgments (such as{% if num > 10 %}It is still treated as a number in calculations or operations.
3. How to keep a number at a specific number of digits when converting it to a string (e.g., leading zeros)?
This isstringformatThe strong point of the filter. You can use%0xdThe format symbol is used to achieve the effect of leading zeros, among whichxrepresents the total number of digits you want.
For example, a number ID is5, you want it to be displayed as005:
{% set product_id = 5 %}
<p>产品编码:{{ product_id|stringformat:"%03d" }}</p> {# 输出: 产品编码:005 #}
Here%03dmeans to format the number as decimal (d), a total of 3 digits(3), if less than 3 digits, pad with zeros in front(0)