How does the Anqi CMS template handle numeric data that may be received as strings from external APIs?

Calendar 👁️ 69

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

Related articles

How to extract part of the numbers from a long ID string for display or logical judgment?

In website operations, we often encounter the need to handle various long string IDs, such as product SKUs, order numbers, user IDs, etc.These ID strings usually contain multiple segments of information, and we may only need part of the numbers for displaying on the page, statistics for reports, or for some business logic judgments.AnQiCMS (AnQiCMS) strong template engine provides us with flexible tools, making it easy to meet such needs.### AnQiCMS template string processing tool: Filter AnQiCMS

2025-11-08

How to perform complex mathematical expression calculations in templates, such as exponentiation or multi-step operations?

In website content management, we often need to handle various data, and this data is not always in its final form.Sometimes, we need to perform simple addition, subtraction, multiplication, and division in templates, and sometimes even more complex mathematical operations, such as calculating squares, cubes, or handling complex expressions with multiple steps.For AnQiCMS users, the good news is that its template engine provides very flexible and powerful mathematical calculation capabilities, allowing us to easily meet these needs.The template system of AnQiCMS is based on Django template engine syntax

2025-11-08

How does `floatformat` prevent the display of the decimal part when a floating-point number is exactly an integer (such as 10.00)?

In website content operation, we often encounter situations where we need to display numbers.These numbers may come from a floating-point type in a database, but in some cases, when they are exactly integers (such as `10.00`, `50.0`), we want them to be presented in a more concise integer form, such as `10` or `50`, rather than with unnecessary decimal parts.AnQiCMS (AnQiCMS) provides powerful template tags and filters, where the `floatformat` filter is a powerful tool to solve such problems

2025-11-08

How to dynamically adjust the decimal precision of displayed numbers in a template?

In website content operation, the precise display of numbers is often crucial, whether it is product prices, statistical data, or technical indicators, the accuracy of decimal point display directly affects the accuracy of information and the understanding of users.AnQiCMS provides a flexible template engine that allows us to easily adjust the decimal precision of numbers in frontend templates, thus satisfying various complex display requirements.The AnQiCMS template system is developed based on Go language, with a syntax style similar to Django, it offers powerful Filter (Filter) functions

2025-11-08

How can percentage data be displayed on a webpage and ensure the correct formatting of decimal places?

In website operation, we often need to display various data, among which percentage data is particularly common.Whether it is the completion, growth rate, discount information or other statistics, it is crucial to present percentages clearly and accurately, and ensure uniformity in the format of decimal places, which is essential for improving user experience and website professionalism.AnQiCMS (AnQiCMS) provides a flexible template system, which can be very convenient to meet this requirement with its powerful filter function.### Data storage: the foundation is crucial In AnQi CMS

2025-11-08

I want to convert the inventory quantity (string) to an integer for comparison, which filter should I use?

In AnQi CMS template development, we sometimes encounter situations where we need to compare data such as product inventory quantity.These quantities may be stored as strings in the content model, for example, a custom field `Stock` of a product model may store such texts as "100", "50", or even "0.5".However, simple string comparison does not meet our needs when performing numerical comparisons, for example, the string "10" will be smaller than the string "2" in string comparison (because '1' is smaller than '2'), which is obviously not consistent with the actual size of the numbers

2025-11-08

How can I avoid scientific notation when displaying floating-point numbers directly in a template?

In the AnQiCMS template, when we need to display floating-point numbers, we sometimes encounter them appearing in scientific notation, such as `1.23E+07` instead of `12,300,000`.This display method is useful in some specific scenarios, but it is often difficult for ordinary users to understand intuitively, affecting the aesthetics and readability of the page, especially in situations where the accuracy is not high but the intuitiveness is required, such as displaying product prices, statistics, etc.AnQiCMS's template engine design borrowed from Django syntax

2025-11-08

Does the `integer` filter round up or down during conversion?

In AnQi CMS template development, data transformation is a common operation, especially when dealing with numbers.We often encounter situations where we need to convert a number that may have decimals into an integer, at which point the `integer` filter comes into play.However, a common question is: when using the `integer` filter for conversion, does it perform ceiling or truncation (floor)?Understanding the working principle of the `integer` filter is crucial for ensuring the accurate display of website data.in short

2025-11-08