In AnQiCMS template, how to judge whether a string can be successfully converted to a numeric type and perform conditional processing?

Calendar 👁️ 63

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

The AnqiCMS template engine (based on Go's Pongo2) provides a rich set of filters (filters) and logical tags, allowing us to flexibly implement this requirement.Below, we will delve into how to complete this task in AnQiCMS templates.

The core mechanism: using built-in filters to determine types

The AnQiCMS template engine does not provide it directlyis_numeric()Such a function to determine whether a string is a number. But we can cleverly use the built-in type conversion filter feature 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 integer representation), 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, it will return0.0.

These filters 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 how to perform judgment and conditional processing through specific examples.

1. Judgment and processing of string to integer conversion

Assuming we have a variablemyStringValueWe want to judge if 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 convertmyStringValueByintegerConvert to integer using the filterconvertedIntIfconvertedIntnot equal to0Then we can be sure that the original string is a non-zero valid integer.

A special case to note: integerThe filter will convert the string"0"and all strings that cannot be converted to numbers (such as"abc") are converted to numbers0. This means that ifconvertedIntThe result is0, we cannot directly determine whether the original string is"0"Other non-numeric strings. To address this edge case, we added a nested one.ifJudgment:{% if myStringValue == "0" %}To clearly distinguish between these two cases, we added a comma.

2. Judgment and processing of string to floating-point number.

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

{% 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"to99.50While transforming"invalid"to0.0. Similarly, whenconvertedFloatWith0.0we check.priceStringIs it"0.0"or"0"To distinguish between the actual zero value and the failure of conversion. Here, we also use extrafloatformat:2a filter to retain two decimal places, making the price display more standardized.

combined with actual needs: comprehensive judgment and processing

In actual projects, we may need to make more flexible presentations based on this judgment result.For example, if the price of some product is not a number, it will display 'price to be discussed';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 shows how tosetLabel the storage of conversion results and useif-elseStructure for multi-level conditional judgments, while combiningadd/floatformatanddefaultOptimize display and calculation with filters.

Points to note

  1. The particularity of the value "0":Always keep in mind.integerandfloatThe filter converts strings"0"(or"0.0"And returns any non-numeric string0(or0.0)。If your business logic needs to strictly differentiate between 'zero value' and 'non-numeric string', please make sure to add an extra comma like in the above example{% if original_string == "0" %}such a judgment
  2. Template logic should be moderate:Although the AnQiCMS template provides powerful logic processing capabilities, it is still recommended to complete the overly complex business logic judgment 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 chaining call:AnQiCMS filters support chained calls, for example{{ myStringValue|trim|float|floatformat:2 }}Before performing type conversion, if the original string may contain extra spaces or other characters, you can usetrimThe filter performs cleaning to improve conversion success rate.

By using the above method, you can effectively determine whether a string is a number in the AnQiCMS template, and according to different conditions, carry out refined conditional processing, thereby building a more robust and user-friendly website feature.


Frequently Asked Questions (FAQ)

1. Whyinteger("0")andinteger("不是数字")The results are all0How can this be distinguished?As mentioned in the article,integerandfloatThe filter will return when it cannot successfully convert a string to a number,0or0.0. If the original string itself is"0"(or"0.0"),the conversion result is also0. To distinguish between these two cases, you need to add a conditional judgment inside the{% if convertedValue == 0 %}code block:{% if originalString == "0" %}This can clearly determine whether the original string is the actual number zero or a non-numeric string.

2. Does AnQiCMS template have built-inis_numericoris_intFunctions of type to judge directly?Currently, the AnQiCMS template engine (Pongo2) does not directly provide something likeis_numeric()oris_int()The built-in function to determine if a string is a number. The method we introduce in our article, that is, to make use ofintegerorfloatThe filter returns when the conversion fails0The feature is currently the recommended way to implement such judgment at the template level.For more complex or performance-sensitive numeric validation, it is usually recommended to process it in the backend Go language code and pass the validation result as a boolean value to the template.

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

Related articles

In AnQiCMS template, how to judge and display the 'In stock' or 'Out of stock' status based on the product inventory (`Stock`) quantity?

It is crucial to clearly communicate the inventory status of products to users in website operations, especially for sites involving product display.This not only optimizes the user experience, reduces invalid consultations, but also effectively guides the user's purchase decision.AnQiCMS as a flexible and efficient content management system, implements the display of "in stock" or "out of stock" status according to the product inventory quantity in the template, which is very intuitive. AnQiCMS template system adopts a syntax similar to Django, which allows us to control the display of page content through concise tags and variables.When processing product information

2025-11-09

How to display different content in the AnQiCMS template based on the value of the `item.Status` field (such as approved, in review)?

In website content operation, the review status of the content is a very important link.Whether it is a comment submitted by the user, a forum post, or an article or product information released by the website administrator, it often needs to be reviewed before it can be displayed to the public.AnQiCMS provides a flexible template mechanism that allows us to easily display different content on the front-end page based on the review status of the content (such as "approved" or "in review"), thereby providing users with clearer and more accurate feedback.AnQiCMS template syntax is similar to the Django template engine

2025-11-09

How to judge if there is a thumbnail in the `archiveList` tag in AnQiCMS template through `if` to selectively display images?

In AnQiCMS template development, displaying list content is a common requirement, and how to elegantly handle the images in these lists, especially thumbnails, is directly related to the visual effects and user experience of the website.The `archiveList` tag is one of the core content call tags of AnQiCMS, which helps us flexibly obtain various document lists.However, in practice, we often encounter situations where certain documents have not set thumbnails, which may lead to broken images or layout confusion on the page. At this time

2025-11-09

In AnQiCMS template, how to judge if the list is empty and display a prompt of 'No content'?

When using AnQiCMS for website template development, you often encounter situations where you need to display list data, such as article lists, product lists, or image galleries.When we retrieve data through template tags (such as `archiveList` or `categoryList`) and use a `for` loop to iterate over the list, if the list is empty, it is usually necessary to provide the user with a friendly prompt instead of displaying a blank space.How can you elegantly judge whether a list is empty in a `for` loop and display a 'No content' prompt?

2025-11-09

What is the default return value when the `integer` and `float` filters fail to convert in the AnQiCMS template?

When building a website on Anqi CMS, we often need to flexibly handle and display data in the template.These, `integer` and `float` filters are very commonly used tools when converting values to integers or floating-point numbers.However, have you ever thought about how the system will handle when these filters receive a value that cannot be recognized as a number?In other words, what default values will these filters return if the conversion operation fails?Understanding this is crucial for us to write robust and predictable template logic.###

2025-11-09

How to determine whether to truncate text and add an ellipsis (...) in AnQiCMS templates based on content length?

In AnQiCMS website content operation, how to elegantly handle long text content to make it both beautiful and complete on the page is the key to improving user experience.Especially on the list page, card display, or introduction area, overly long text often leads to layout confusion and affects the overall visual effect.AnQiCMS' powerful template engine provides various flexible ways to solve this problem, the most commonly used being the function of text truncation and adding ellipses.The AnQiCMS template system borrows the syntax of the Django template engine

2025-11-09

What are the respective application scenarios of the `striptags` and `removetags` filters when cleaning HTML code in AnQiCMS templates?

In AnQiCMS template design, we often encounter situations where we need to clean up or simplify the HTML code in the content.This is not just for beauty, but also to ensure the correct display of content, improve page loading efficiency, and even prevent potential security risks.The Aqie CMS provides two very practical filters: `striptags` and `removetags`.Although they are all related to the removal of HTML tags, each has a clear application scenario.### `striptags`

2025-11-09

How can AnQiCMS templates safely display user-submitted rich text content to prevent potential XSS attacks?

During website operations, displaying rich text content submitted by users, such as article comments, forum posts, or blog content, is an unavoidable requirement.However, there may be malicious scripts hidden in these contents, and if they are displayed without precautions, it may lead to cross-site scripting (XSS) attacks, posing potential threats to website visitors.AnQiCMS (AnQiCMS) has fully considered this security risk in its design and provides a series of mechanisms through its template engine to help us safely handle this type of rich text content.

2025-11-09