In the template creation of Anqi CMS, we often encounter situations where we need to process strings input by users or obtained from the database.One common requirement is: to determine whether a string can be successfully converted to a numeric type, and to perform different conditional processing based on the result of the judgment.This is crucial for data display, calculation, and even simple form validation.

The template engine of AnQi CMS (based on Go language's Pongo2) provides rich filters and logical tags, allowing us to flexibly implement this requirement.Below, let's delve into how to complete this task in the AnQiCMS template.

Core Mechanism: Use built-in filter to judge type

AnQiCMS template engine does not provide directlyis_numeric()Such a function to determine whether a string is a number. But, we can cleverly use the characteristics of its built-in type conversion filter to achieve this.

The two most critical filters areintegerandfloat:

  • integerFilterAttempt to convert a value to an integer. If the conversion is successful, it will return the corresponding integer value; if the conversion fails (for example, the string is not a valid representation of an integer), it will return0.
  • floatFilterAttempt to convert a value to a floating-point number. If the conversion is successful, it will return the corresponding floating-point value; if the conversion fails,0.0.

it is these filters that return when the conversion fails0or0.0The characteristic, became the key clue for us to judge whether a string can be converted to a number.

Conditional judgment and practical application

Let us demonstrate through specific examples how to perform judgment and conditional processing.

1. Judgment and handling of string to integer conversion

Suppose we have a variablemyStringValueWe want to judge whether it can be converted to an integer.

{% set myStringValue = "123" %} {# 假设从数据源获取的值 #}
{% set convertedInt = myStringValue|integer %}

{% if convertedInt != 0 %}
    <p>该值是一个有效的整数:{{ convertedInt }}</p>
    <p>进行一些计算:{{ convertedInt | add:10 }}</p>
{% else %}
    {# 进一步判断是否原始值就是 "0" #}
    {% if myStringValue == "0" %}
        <p>该值是数字“0”</p>
    {% else %}
        <p>该值不是有效的整数,无法进行数字运算。</p>
    {% endif %}
{% endif %}

In the above example, we first try to convertmyStringValuePassintegerthe filter to an integerconvertedInt.convertedIntNot equal to0, then we can be sure that the original string is a non-zero valid integer.

One special case to note: integerThe filter will convert strings to"0"and all strings that cannot be converted to numbers (e.g."abc") to numbers.0This means that ifconvertedIntThe result is0, we cannot directly determine the original string is"0"Or other non-numeric strings. To address this edge case, we added a nestedifJudgment:{% if myStringValue == "0" %}, to clearly distinguish between these two cases.

2. The judgment and handling of converting a string to a floating-point number.

Similar to integers, the logic to determine whether a string can be converted to a floating-point number is the same.

{% set priceString = "99.50" %} {# 假设一个价格字符串 #}
{% set convertedFloat = priceString|float %}

{% if convertedFloat != 0.0 %}
    <p>商品价格:¥{{ convertedFloat }}</p>
    <p>折扣后价格:¥{{ convertedFloat * 0.8 | floatformat:2 }}</p>
{% else %}
    {# 同样考虑 "0.0" 的特殊情况 #}
    {% if priceString == "0.0" or priceString == "0" %}
        <p>商品价格为零。</p>
    {% else %}
        <p>商品价格信息无效,请联系客服。</p>
    {% endif %}
{% endif %}

Here,floatThe filter will"99.50"Converted to99.50, and to convert"invalid"Converted to0.0. Similarly, whenconvertedFloatresponse for0.0When, we checkpriceStringIs it"0.0"or"0"to distinguish the actual zero value and conversion failure situations.floatformat:2a filter is also used to retain two decimal places, making the price display more standardized.

Combine actual requirements: Comprehensive judgment and processing

In practical projects, we may need to make the display more flexible based on this judgment result.For example, if the price of an item is not a number, display 'Price to be negotiated'; if it is a number, display the specific price and perform the calculation.

{% set productPrice = "面议" %} {# 模拟一个非数字价格 #}
{# {% set productPrice = "128.00" %} #} {# 模拟一个数字价格 #}

{% set priceAsFloat = productPrice|float %}

<div class="product-info">
    {% if priceAsFloat != 0.0 %}
        {# 确认是有效非零数字,或者原始字符串就是“0”/“0.0”的情况 #}
        {% if productPrice == "0" or productPrice == "0.0" %}
            <p>商品价格:免费</p>
        {% else %}
            <p>商品价格:<strong>¥{{ priceAsFloat | floatformat:2 }}</strong></p>
            <p>会员折扣价:<strong>¥{{ (priceAsFloat * 0.9) | floatformat:2 }}</strong></p>
        {% endif %}
    {% else %}
        {# 原始字符串不是“0”/“0.0”且转换失败的情况 #}
        <p>商品价格:<span>{{ productPrice | default:"价格待议" }}</span></p>
    {% endif %}
</div>

This example demonstrates how tosetLabel the conversion results and useif-elseStructure for multi-level conditional judgment, while combiningadd/floatformatanddefaultOptimize display and calculation with filters.

Precautions

  1. Speciality of the value “0”:Always remember tointegerandfloatConvert strings with filters"0"(or}"0.0", and it will return for any non-numeric string.0(or}0.0)。If your business logic requires strict differentiation between 'zero value' and 'non-numeric string', please make sure to add such a judgment as shown in the above example.{% if original_string == "0" %}such a judgment.
  2. Template logic moderately:Although AnQiCMS templates provide powerful logic processing capabilities, it is still recommended to complete overly complex business logic judgments on the backend (Go language code) and pass the processed data to the template for display.This can maintain the simplicity of the template, improve readability and maintainability.
  3. Filter chain calling:AnQiCMS supports filter chain calling, for example:{{ myStringValue|trim|float|floatformat:2 }}Before performing type conversion, if the original string may contain extra spaces or the like, you can first usetrima filter to clean up, improving the success rate of conversion.

By using the above method, you can effectively determine whether a string is a number in the AnQiCMS template and perform fine-grained condition handling based on different situations, thereby building more robust and user-friendly website features.


Common Questions (FAQ)

1. Whyinteger("0")andinteger("不是数字")The results are0How should this be distinguished?As mentioned in the article,integerandfloatThe filter will return0or0.0If the original string itself is"0"(or}"0.0"), the conversion result is also0. To distinguish between these two cases, you need to add another conditional judgment inside{% if convertedValue == 0 %}the code block:{% if originalString == "0" %}[en] Such that it can be clearly determined whether the original string is actually the number zero or a non-numeric string.

[en] Whether there is an embedded AnQiCMS template.is_numericoris_intIs there a function type to directly judge?Currently, the template engine (Pongo2) of AnQiCMS does not provide a direct equivalent tois_numeric()oris_int()The built-in function to determine if a string is a number. The method we introduce in our article, that is, utilizingintegerorfloatfilter returns when the conversion fails0The feature, currently the recommended way to implement such judgment at the template level, is.For more complex or performance-intensive numeric validations, it is typically recommended to process them in the backend Go language code and pass the validation results as boolean values to the template.

3. If a string cannot be converted to a number, I want to display an empty string instead0How can this be achieved?You can combine the use ofintegeror