In AnQiCMS template development, we often encounter scenarios where we need to display numeric data combined with text content.For example, you may need to add the product ID after a product title, or add the text 'times read' after the number of reads in an article.When dealing with such requirements, a common issue is: how to flexibly convert the numeric fields in the template to strings and concatenate them without affecting other logical judgments or calculations?

幸运的是,AnQiCMS强大的Django-like模板引擎(Pongo2)为我们提供了多种简洁有效的方法来解决这个问题,无论是隐式转换还是显式控制,都能轻松应对。


The most direct way: implicit conversion

In AnQiCMS templates, you often don't need any special operation.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 this number to a string form for output.

For example, if you have an article object's ID field (suppose)archive.IdIt is a number), and you want to display it in the 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 a numeric type, the template engine will automatically complete the conversion to a string and then concatenate it with the surrounding text, thus displaying the complete text you expect on the page.This method is simple and direct, suitable for most scenarios that only need to display numeric content.

Flexible combination:addFilter

When you need to combine numbers with strings or other numbers more explicitly, or in complex scenarios that require variable concatenation,addA filter is a very practical tool.addThe filter can be used to add two values.If both of these 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 string concatenation.

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 results like '12345 views' (assumingarchive.ViewsThis provides great flexibility when you need to dynamically combine strings and numbers from different sources.

Fine control:stringformatFilter

If simply converting and concatenating is not enough, you may need to have more fine-grained control over the display format of numbers, such as retaining a specific number of decimal places, padding with leading zeros, or displaying in a monetary format. At this point,stringformatThe filter comes into play.

stringformatThe filter allows you to use Go language'sfmt.Sprintf()The format string of style, which converts any value type (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's less than 4 digits, it should be filled with zeros in front:

{% set item_id = 7 %}
<p>商品编号:{{ item_id|stringformat:"商品ID:%04d" }}</p> {# 输出: 商品ID:0007 #}

PassstringformatYou can fully control the appearance of numbers when converted to strings, ensuring it meets the strict requirements of page design, while also being convenient to concatenate with other string content.


Summary

In AnQiCMS templates, converting a numeric field to a string and concatenating it is not a difficult task. For most simple display requirements, 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,stringformatFilterThen it is the preferred method to achieve this goal.

These methods only affect the 'presentation' of data in the template and will not change the original data type of the variables. Therefore, 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, which can make your template code clearer and more efficient.


Common 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 numeric 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?

English. The template filter of AnQiCMS mainly handles the "display" logic of variables in the template. When you useaddorstringformatThe filters convert numbers to strings for concatenation, which is just a "formatting output" at the current output stage. The original number variable still maintains its numeric type in the context of the template, and remains in subsequent logical judgments (such as{% if num > 10 %})or in calculation, it is still considered a number.

3. How to keep a specific number of digits when converting a number to a string (e.g., adding zeros in front)?

This is exactlystringformatis the strong point of the filter. You can use%0xdThis format symbol is used to achieve the effect of leading zeros, wherexrepresents the total number of digits you want.

For example, a numeric ID is5and 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),总共3位(3),不足3位时前面补零(0).