English CMS provides an elegant solution with its flexible template engine and rich data processing capabilities.它采用了类似Django模板引擎的语法,其中强大的“过滤器(Filters)”功能,便是处理这类数据类型不确定性的关键利器。
Understanding the problem: Uncertainty of external API data types
External API designers may wrap numerical data into strings for various reasons. For example, a price field{"price": "19.99"}or a stock quantity{"stock": "100"}. When directly referencing these data in the Anqi CMS template, if the template expects a number for arithmetic operations or needs to display a specific numerical format (such as retaining two decimal places), then directly outputting a string may result in:
- Display exception:The string cannot be directly formatted as a number, it may be output as "19.99 yuan" instead of the formatted "¥19.99."
- Calculation error:Attempt to perform mathematical operations on strings usually results in errors or unexpected outcomes (for example, “10” + “20” might result in “1020”, not 30).
- Condition judgment error:Expected to use numerical values for
{% if item.stock > 0 %}Such judgment, but strings may cause logical confusion.
The powerful tool of Anqi CMS template: Data filter
The template engine of AnQi CMS is built-in with a variety of filters, allowing us to perform various transformations and processing on variables, including type conversion and formatting. These filters are implemented through the pipe character|Use it, can be chained, which greatly facilitates data processing.
The core numerical processing filters include:
integer:Try to convert the variable to an integer.float:Try to convert the variable to a floating-point number.floatformat:Format floating-point numbers, controlling the number of decimal places.stringformat:Output strings or numbers in a specified format (such as Go language's)fmt.SprintfFormat) output strings or numbers.default/default_if_none:Set default value for empty or undefined variables to avoid blank.
Common scenarios and solutions
Scenario one: Convert a string to a number for calculation or display.
Suppose we get the price of a product from the API.item.api_priceand stock.item.api_stockThey are all strings.
Solution:UseintegerorfloatFilter to perform type conversion. For robustness, it is usually combined withdefaultFilter sets a default value to prevent failure during conversion or if data is empty.
{# 将字符串价格转换为浮点数,并设置默认值为0.00 #}
{% set price = item.api_price|float|default:0.00 %}
{# 将字符串库存转换为整数,并设置默认值为0 #}
{% set stock = item.api_stock|integer|default:0 %}
<p>产品价格:{{ price }} 元</p>
<p>当前库存:{{ stock }} 件</p>
<p>总价值:{{ price|add:10.00|floatformat:2 }} 元 (假设加了运费)</p>
Here,|floatand|integerAttempts to convert the string to the corresponding numeric type. If the conversion fails (for example, the string is "abc"), they return 0 or 0.0,|defaultThe filter ensures that the preset default values are provided in these cases, thus avoiding template errors.
Scenario two: Formatting numerical display
The display format of the values may still need to be controlled after the conversion, such as currency display, percentage display, etc.
Solution:UsefloatformatorstringformatFilter.
{# 将价格保留两位小数 #}
<p>产品价格:¥{{ item.api_price|float|floatformat:2 }}</p>
{# 将一个温度值格式化为“25.5 度” #}
{% set temp = item.api_temperature|float|default:0.0 %}
<p>当前温度:{{ temp|stringformat:"%.1f 度" }}</p>
{# 将一个字符串化的时间戳转换为可读日期 #}
{% set timestamp_str = item.last_update_time|default:"0" %}
<p>最后更新:{{ stampToDate(timestamp_str|integer, "2006-01-02 15:04") }}</p>
floatformat:2The floating-point number will be formatted to two decimal places.stringformatIt provides more powerful format control capabilities, similar to how Go language uses%Placeholders. For timestamp strings, we usually need to convert them to integers first|integer), and then throughstampToDateLabel formatting.
Scene three: Handling possibly null numeric data for conditional judgment
Sometimes, the numeric data returned by the API may be missing, appearing asnullEnglish translation: The value can be an empty string, or the field may not exist. Direct numerical comparison may result in errors.
Solution:Combineifsentences anddefaultFilter.
<p>享受折扣:{{ discount|floatformat:2 }} 元</p>
{% else %} English
<p>暂无折扣</p>
{% endif %}