How to get a specific digit from a number: Advanced usage of the `get_digit` filter in AnQiCMS template?

Calendar 👁️ 67

In AnQiCMS template development, flexible handling and displaying data is the key to enhancing website functionality and user experience.When faced with a series of numbers, such as product numbers, order numbers, or some kind of identification code, sometimes we do not need the entire number, but rather a specific digit at a certain position.get_digitThe filter has become a very practical tool.It can help us accurately extract the required part from numbers, providing more possibilities for the dynamic display of templates and logical judgment.

Core function: understandget_digitFilter

get_digitThe main function of the filter is to obtain a single digit from a number at a specified position. One of its unique features is that the calculation of the position starts from the number'sthe last onestarting, and the index from1start counting.

For example, if there is a number1234567890:

  • Get the last one (get_digit:1),The result is0.
  • Get the second last one (get_digit:2),The result is9.
  • Get the third last one (get_digit:3),The result is8.

Here is the basic usage:

{{ 源数字 | get_digit:位置 }}

Among them,源数字Is the number you want to process,位置It is an integer representing the position from the end you want to get the number.

It is worth noting that if the specified位置exceeds源数字of the actual number of digits,get_digitThe filter does not report an error, but instead returns the original源数字. This can be used as a simple boundary condition handling mechanism when dealing with numbers of different lengths.

Advanced Usage One: The Subtle Control of Numeric Sequences

get_digitThe filter shows its powerful practicality when it needs to dynamically control logic or style based on specific positions of numbers.

Imagine a scenario, where you would like to display different icons, colors, or layouts based on a certain digit of the product ID. For example, on an e-commerce website, the product ID is12345. You may want to display a red label for products with an odd ID ending and a blue label for even ones.

{% set productId = 12345 %}
{% set lastDigit = productId | get_digit:1 %} {# 获取末位数字,结果是 5 #}

{% if lastDigit % 2 == 0 %}
    <span class="product-tag product-tag-blue">热销</span>
{% else %}
    <span class="product-tag product-tag-red">新品</span>
{% endif %}

Byget_digit:1ObtainproductIdthe last digit, combined with simple modulo operations.lastDigit % 2 == 0It can easily achieve this kind of dynamic judgment.

Another example is that when displaying a series of contents, you may want to adjust the style at regular intervals. Althoughforloop.CounterIt can meet similar needs, but if your logic is based onIDinstead of the number of loops,get_digitit is very useful. For example, you want to产品IDthe second last digit of0At this time, add a special border to the product list item:

{% for product in productList %}
    {% set secondLastDigit = product.Id | get_digit:2 %}
    <div class="product-item {% if secondLastDigit == 0 %}highlight-border{% endif %}">
        {# 产品详情 #}
        <h3>{{ product.Title }}</h3>
        <p>ID: {{ product.Id }}</p>
    </div>
{% endfor %}

Advanced usage two: hidden treasure of string operations

This isget_digitA filter that is not very intuitive but may be helpful in certain specific scenarios. Although its name suggests it is used for numbers, when源数据Is astringthen,get_digitThe filter will exhibit a special behavior: it will convert the character at a specified position in the string to its corresponding numeric value.

In particular, it will take the character at the position in the string, then get the ASCII code of the character, and then subtract the ASCII code of the number '0' (which is 48).So, if the position is exactly a numeric character ('0' to '9'), you can get the number it represents.If it is not a numeric character, you will get a non-expected number based on its ASCII code.

For example:

{{ "anqicms" | get_digit:2 }} {# 'n' 的ASCII码减去'0'的ASCII码,结果是 61 #}
{{ "ANQICMS" | get_digit:2 }} {# 'N' 的ASCII码减去'0'的ASCII码,结果是 29 #}
{{ "安企CMS" | get_digit:2 }} {# 汉字 '企' 的ASCII码减去'0'的ASCII码,结果是 139 #}
{{ "Product123" | get_digit:3 }} {# 获取倒数第三个字符 '1',结果是 1 #}

Even though this behavior may not be commonly used in regular content operations, as it deals with the ASCII values of characters rather than the literal extraction of numbers, it may come in handy in very few cases where you need to numerize characters at specific positions in a string (for example, some encoding or verification mechanism). But usually, if you need to extract numbers from a string, it is recommended to use string processing functions (such assplitCombineintegerFilter to get more controllable results.

Practical case: Make the template smarter

  1. Dynamic style or class name generationWe can dynamically add CSS classes to HTML elements based on the specific digit positions of a data ID or serial number to achieve visual diversity.

    <div class="product-card product-variant-{{ product.id | get_digit:1 }}">
        {# ...产品内容... #}
    </div>
    

    Thus, cards with product ID ending in 1 will receiveproduct-variant-1class, those ending in 2 will receiveproduct-variant-2for fine-grained control of CSS.

  2. content grouping or data distributionWhen displaying a large amount of data, if you want to group or filter the data based on a certain feature (such as a number in the ID) initially, you can use it on the front-end.get_digitImplementation.

    {% for item in archiveList %}
        {% set categoryBucket = item.id | get_digit:2 %} {# 获取ID的倒数第二位 #}
        {% if categoryBucket == 3 %}
            <p>这是ID倒数第二位是3的特别推荐内容:{{ item.title }}</p>
        {% endif %}
    {% endfor %}
    
  3. Simplified data display: Sometimes, only a few digits of a long number (such as a serial number) are needed to identify it in display.get_digitIt can help you extract the most critical digits.

    <p>您的订单号尾号是:{{ order.number | get_digit:1 }}{{ order.number | get_digit:2 }}</p>
    

Points to note

  • Counting method: Be sure to remember.get_digitIs from the number of thethe last oneStart counting and the index from1.
  • Data type: Although it can be used on strings, its behavior is based on ASCII value conversion. Be cautious when handling data other than numbers, and thoroughly test it.
  • Combine with other filters:get_digitCan be combined with other filters (such asifJudgment,setAssignment) to build more complex template logic.

By deep understandingget_digitThese advanced usage and注意事项 of the filter, you will be able to handle numeric data more flexibly in the AnQiCMS template, bringing users a smarter and more personalized content display experience.


Frequently Asked Questions (FAQ)

Q1:get_digitIf omitted in the filternumberor set it to0What will happen?A1: If you omitnumberParameters (for example{{ 12345 | get_digit }}or set it to0for example{{ 12345 | get_digit:0 }})get_digitThe filter returns the complete original number. This actually means it does not extract any specific

Related articles

Template content shows: How does the `truncatewords` filter truncate text by word count?

In the presentation of website content, we often need to condense lengthy text information to meet different layout requirements, such as displaying article summaries on list pages, brief descriptions on product cards, etc.This not only makes the page look neater, but also helps visitors quickly grasp the core information.AnQiCMS provides flexible template filters for this type of need, where the `truncatewords` filter is your powerful assistant for truncating text by word count.### A clever and concise summary, making the content clear at a glance

2025-11-08

How to safely truncate the article content using the `truncatechars_html` filter without destroying the HTML structure for website SEO?

In website operation, we often need to display the concise content of articles in article lists, search results summaries, or social media shares.This concise content should not only attract users' attention, but also ensure that the complex HTML structure behind it is not damaged, in order to avoid affecting the layout and user experience.For search engine optimization (SEO), a clean and effective code structure is crucial. AnQiCMS (AnQiCMS) is an enterprise-level content management system developed based on the Go programming language, deeply understanding the pain points and needs of website operation.It not only provides multi-site management, a flexible content model

2025-11-08

Array concatenation into a string: Application scenarios of the `join` filter in AnQiCMS templates?

In website content management, we often encounter the need to display a set of data, such as multiple tags, multiple image URLs, or custom multiple-choice content, in a unified string format.AnQiCMS (AnQiCMS) boasts its efficient architecture based on the Go language and a flexible template engine similar to Django, providing great convenience for content display.Today, let's delve deeper into a very practical tool for handling such needs - the `join` filter.What is the `join` filter? In the AnQi CMS template world

2025-11-08

What is the difference between the `make_list` filter and the `split` filter? When should `make_list` be used to split strings?

In AnQi CMS template development, we often need to process string data, such as splitting a long string into multiple independent parts for traversal, display, or further logical judgment.Anqi CMS provides a variety of filters (Filters) to help us complete these tasks, among which `make_list` and `split` are two commonly used string splitting tools.Although they can all convert strings to lists (or arrays), there are obvious differences in their functional focus and usage scenarios.

2025-11-08

What is the role of the `index` filter in processing string searches?

In the AnQiCMS template world, efficiently processing and displaying content is the core.Whether it is to dynamically adjust the page display based on user input or quickly locate key information in complex text, mastering the template function can greatly improve the operation efficiency of your website content.Today, let's delve into a very practical tool for string searching—the `index` filter.### `index` filter: 'Locate Expert' string Imagine you have a long article content or a list with multiple tags

2025-11-08

How to replace a specific keyword with another in AnQiCMS template?

In the flexible template system of AnQiCMS, dynamic content processing is an indispensable part of daily operation.Sometimes, we may need to replace a specific keyword in a string when displaying content, such as displaying a brand name uniformly or adjusting the presentation of certain text without modifying the original data.AnQiCMS's template engine provides a concise and efficient method to complete this task, among which the `replace` filter is our powerful assistant.###

2025-11-08

Remove extra spaces or specific characters from a string, which filter should be used first (`cut` or `trim`)?

In the template world of Anqi CMS, we often need to clean and format strings, such as removing extra spaces from user input or dealing with specific symbols mixed in with imported content from external sources.At this point, the `cut` and `trim` filters have become our reliable assistants.Although they can all 'remove characters', their working methods and applicable scenarios are fundamentally different.Understanding the difference between these two can help us handle content more efficiently and accurately, making the website display more professional and tidy.

2025-11-08

`trim`, `trimLeft`, `trimRight` filters specific usage scenarios and differences in AnQiCMS templates?

In AnQiCMS template development, handling and optimizing the display of page content is one of the daily tasks.We often need to process the data obtained from the backend to ensure that it is neat and meets expectations on the frontend.Among them, the cleaning of strings, especially the removal of redundant whitespace characters or specific characters, is a key factor in improving content quality and user experience.The AnQiCMS template system provides several very practical filters: `trim`, `trimLeft`, and `trimRight`.They each have their own unique uses and application scenarios.

2025-11-08