In the template development of Anqi CMS, we often encounter scenarios where we need to handle numeric string.For example, the price stored in the custom field on the backend may be a text type "5.5", or the number may exist as a string in the data obtained through an external API.At this point, if you perform a numerical calculation directly, you may encounter problems.However, AnqiCMS's template engine provides very flexible and powerful features, which can easily convert a numeric string to a floating-point number or an integer and then perform subsequent display and calculation.
Deep Understanding of Number Processing in AnqiCMS Templates
AnqiCMS uses a syntax similar to the Django template engine, which makes it somewhat intelligent in handling data. When the variable received by the template itself is of numeric type (for example, it has been defined as a number in the Go backend code,int/float64English),you can directly perform arithmetic operations such as addition, subtraction, multiplication, and division in the template, for example{{ item.price * 0.8 }}to calculate the price after an 80% discount.
However, when data is passed in as a string, for example"5.5"Directly performing mathematical operations may result in unexpected outcomes, even errors.AnqiCMS provides a special "filter" (Filters) for this, which acts like a "pipeline" for data processing, enabling the transformation, formatting, or processing of data to meet our needs.
核心转换利器:EnglishfloatandintegerFilter
为了将数字字符串安全地转换为可计算的数值,AnqiCMS模板提供了Englishfloatandinteger这两个关键过滤器。English
float过滤器:转换为浮点数EnglishWhen you need to convert a numeric string that may contain decimals into a floating-point number,floatFilter is an ideal choice. It will attempt to parse the string, and if successful, it will return the corresponding floating-point value (for example5.5will be converted to5.5). If the string cannot be parsed as a valid floating-point number (for example"foobar"),It will return0.0,This is very useful when handling potential error data.The usage is usually like this:
{% set priceString = "5.5" %} {% set priceFloat = priceString|float %} <p>转换后的浮点数:{{ priceFloat }}</p> {# 输出 5.500000 #} {% set invalidString = "invalid_number" %} {% set invalidFloat = invalidString|float %} <p>无效字符串转换结果:{{ invalidFloat }}</p> {# 输出 0.000000 #}integerFilter: Convert to integerIf you are sure that the numeric string is an integer, or you want to truncate a floating-point number to an integer, thenintegerThe filter comes in handy. It will try to parse the string as an integer (for example"100"will be converted to100)。如果字符串包含小数,它会将其向下取整(例如"5.6"will be converted to5)。同样,如果无法解析为有效数字,它将返回0.The usage is as follows:
{% set countString = "100" %} {% set countInteger = countString|integer %} <p>转换后的整数:{{ countInteger }}</p> {# 输出 100 #} {% set floatString = "5.6" %} {% set floatToInteger = floatString|float|integer %} {# 先转浮点再转整数,得到 5 #} <p>浮点字符串转换为整数:{{ floatToInteger }}</p> {# 输出 5 #} {% set anotherInvalidString = "another_invalid" %} {% set anotherInvalidInteger = anotherInvalidString|integer %} <p>另一个无效字符串转换结果:{{ anotherInvalidInteger }}</p> {# 输出 0 #}It is worth noting that you can chain multiple filters together for use, as shown above
floatString|float|integerlike the example, the data will pass through each filter in turn.
Perform numerical calculation
Once the numeric string is successfully convertedfloatorintegerAfter the type, you can perform various arithmetic operations on the template as with any other number.
For example, calculate the discounted price:
{% set originalPriceString = "100.50" %}
{% set discountRate = 0.75 %} {# 75折 #}
{% set convertedPrice = originalPriceString|float %}
{% set finalPrice = convertedPrice * discountRate %}
<p>最终价格:{{ finalPrice }}</p> {# 输出 75.375 #}
AnqiCMS also providesaddFilter, although it is more direct to use+symbols for addition operations are usually more intuitive, butaddFilter provides an option in some scenarios (such as when adding a known number to a variable that may not be a number, and ensuring error handling).
{% set baseValue = 10 %}
{% set additionalString = "5" %}
{% set total = baseValue|add:additionalString|integer %} {# 10 + 5 = 15 #}
<p>使用add过滤器进行相加:{{ total }}</p> {# 输出 15 #}
Display and Format Numbers
After the numerical calculation is completed, we often need to format the result to make it more in line with the display habits, such as retaining two decimal places.
floatformatFilter: Control Decimal PlacesfloatformatThe filter allows you to precisely control the number of decimal places in floating-point numbers. By default, it retains one decimal place, and if the last digit is 0, it is omitted. You can specify a specific number of digits.{% set rawPrice = "75.375"|float %} <p>默认格式化:{{ rawPrice|floatformat }}</p> {# 输出 75.4 #} <p>保留两位小数:{{ rawPrice|floatformat:2 }}</p> {# 输出 75.38 #} <p>保留零位小数(四舍五入):{{ rawPrice|floatformat:0 }}</p> {# 输出 75 #}stringformatFilter: Advanced FormattingFor more complex number formatting needs, such as adding thousand separators, currency symbols, or padding zeros,stringformatThe filter provides powerful Go languagefmt.Sprintf()formatting capabilities of style.{% set totalAmount = "12345.678"|float %} <p>货币格式化:{{ totalAmount|stringformat:"$%.2f" }}</p> {# 输出 $12345.68 #} <p>整数填充:{{ 5|stringformat:"%03d" }}</p> {# 输出 005 #}
Comprehensive Example
The item has a priceitem.priceIt is sent from the backend but may be a string, stock levelitem.stockIt is also a string, you need to display the discounted price on the page and check if the stock is sufficient.
{% set itemPriceString = "128.99" %}
{% set itemStockString = "5" %}
{% set minStockRequired = 3 %}
{# 转换为数值类型 #}
{% set price = itemPriceString|float %}
{% set stock = itemStockString|integer %}
{# 进行计算 #}
{% set discountedPrice = price * 0.90 %} {# 九折 #}
<p>商品原价:{{ price|floatformat:2 }} 元</p>
<p>九折后价格:{{ discountedPrice|floatformat:2 }} 元</p>
{# 进行条件判断 #}
{% if stock > 0 %}
<p>当前库存:{{ stock }} 件</p>
{% if stock >= minStockRequired %}
<p>库存充足,欢迎购买!</p>
{% else %}
<p>库存紧张,请尽快下单!</p>
{% endif %}
{% else %}
<p>商品已售罄。</p>
{% endif %}
By using flexibilityfloatandintegerFilter, combined with arithmetic operators andfloatformat/stringformatEnglish display filter, you can easily handle the processing of numeric strings in the AnqiCMS template and achieve various complex display and calculation logic.
Common Questions (FAQ)
问:Why do I need to explicitly convert a string of numbers to a floating-point number or an integer? AnqiCMS template engine cannot recognize it automatically?答:AnqiCMS的模板引擎在处理字面量数字时(例如 English
{{ 10 + 5 }})Indeed, it can automatically recognize. But when the data source is a variable, and the value of the variable is a string that looks like a number (for example"5.5"),Template engine usually treats it as plain text. To ensure the accuracy of subsequent mathematical operations or comparisons, it is explicitly usedfloatorintegerFiltering is** practical, as it avoids errors due to mismatched data types.**Q: If my numeric string contains non-numeric characters