In website operation, we often encounter situations where we need to integrate data from different external APIs.These APIs provide a variety of data types, and the formats are also different, especially when dealing with numerical data, we may find that fields that should be numbers such as 'price', 'inventory', or 'rating' are returned as strings.This not only causes trouble for template display, but may also affect data calculation and subsequent processing.

The AnQi CMS, with its flexible template engine and rich data processing capabilities, provides us with an elegant solution.It adopts a syntax similar to the Django template engine, where the powerful "Filters" feature is the key tool for dealing with uncertain data types.

Understanding the issue: Uncertainty in external API data types

For various reasons, external API designers may wrap numerical data in strings. For example, a price field{"price": "19.99"}Or an inventory quantity{"stock": "100"}. When we directly reference this data in the AnQi CMS template, if the template expects a number for arithmetic operations such as addition, subtraction, multiplication, or needs to display a specific number format (such as retaining two decimal places), then directly outputting a string may result in:

  1. Display Exception:The string cannot be formatted numerically directly, it may output “19.99 Yuan” as is, rather than the formatted “¥19.99”.
  2. Calculation Error:Try performing mathematical operations on strings, which usually leads to errors or unexpected results (for example, “10” + “20” may result in “1020”, not 30).
  3. The condition judgment was incorrect:Expected to use numerical values to{% if item.stock > 0 %}such a judgment, but strings may cause logical confusion.

The weapon of the Anqi CMS template: Data Filter

The AnQi CMS template engine is built-in with multiple filters that allow us to perform various transformations and processing on variables, including type conversion and formatting. These filters are passed through the pipe character|Use it, it can be chained, which is very convenient for data processing.

The core numeric 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)
  • default/default_if_none:Set a default value for empty or null variables to avoid gaps.

Common scenarios and solutions

Scenario one: Convert strings to numbers for calculation or display.

Assuming we get the price of a product from the APIitem.api_priceand stockitem.api_stockThey are all strings.

Solution:UseintegerorfloatFilter to perform type conversion. For robustness, it is usually combined withdefaultThe filter sets a default value in case of conversion failure or empty data.

{# 将字符串价格转换为浮点数,并设置默认值为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 a string to its corresponding numeric type. If the conversion fails (for example, the string is 'abc'), they return 0 or 0.0,|defaultThe filter can ensure that the default values we set are provided in these cases, thus avoiding template errors.

Scenario two: Formatting number display

After the number conversion is successful, we may still need to control their display formats, 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:2It will format the floating-point number to two decimal places.stringformatIt provides more powerful format control capabilities, similar to the use in Go language%Placeholder. For timestamp strings, we usually need to convert them to integers first (|integer), and then throughstampToDateFormat labels.

Scene three: Handle conditional judgment for potentially empty numeric data

Sometimes, the API returns missing numeric data, which may be indicated bynullThis is a string, even an empty string or a missing field. Direct numerical comparison may result in errors.

Solution:CombineifAnd statementdefaultfilter.

`twig {% set discount = item.api_discount|float|default:0.0 %} {% if discount > 0.0 %}

<p>享受折扣:{{ discount|floatformat:2 }} 元</p>

{% else %}

<p>暂无折扣</p>

{% endif %}

{# Check if a numeric field exists or has a valid value #} {% set rating = item.api_rating|float %} {% if rating %} {# 0.0 is also considered False