In the daily operation of websites, we often encounter situations where we need to handle various encodings or IDs, such as product codes, order numbers, batch numbers, etc. They often contain multiple segments of information, and we may only need to extract a part of the numbers from them.For example, from the complex product code “PROD20230815BATCH007”, we only want to quickly obtain “007” as the batch number.
The Aanqi CMS can easily meet such requirements with its flexible content model and powerful template tag system.接下来,我们将探讨如何在安企CMS中,利用其内置的过滤器功能,从数字字符串中精准提取指定位置的数字。
First step: Preparation - Define content model and fields
Firstly, we need to make sure that your product codes and other information are stored in the content model of the Anqi CMS. If you don't have a dedicated field to store these codes, you can set it up by following the following steps:
- Log in to the Anqi CMS backend and navigate to 'Content Management' under 'Content Model'.
- You can choose to modify the existing content model (such as "product model" or "article model"), or create a completely new content model.
- On the selected model editing page, find the "Content Model Custom Fields" section.Here, you need to add a new field, such as named 'Product Code', and the field type is recommended to be 'Single Line Text'.So, when publishing or editing product content, you can enter the complete product code in this field.
Suppose we have created a namedproduct_codeThe custom field, used to store product code.
Step two: Call the product code in the template.
On our website frontend, whether it is a product detail page or a product list page, we need to first obtain the field value that includes the complete encoding. The Anqi CMS providesarchiveDetailandarchiveListLabels to help us achieve this.
If you are on the product details page (usually corresponding to)detail.htmltemplate), you can directly accessarchiveDetailthe label to get the current product'sproduct_codefield value:
{% archiveDetail productCode with name="product_code" %}
{% set fullProductCode = productCode %}
If you are on the product list page (usually correspondinglist.htmltemplate), you need toarchiveListget each product in the tag loopproduct_codefield value:
{% archiveList archives with moduleId="你的产品模型ID" type="page" limit="10" %}
{% for item in archives %}
{% set fullProductCode = item.product_code %}
{# 接下来在这里处理 fullProductCode #}
{% endfor %}
{% endarchiveList %}
Now, we have stored the complete product code infullProductCodeIn the variable, the next step of number extraction can be performed.
Step 3: Extract the number at the specified position.get_digitThe filter takes action.
AnQi CMS is built-in with a very practical feature.get_digitFilter, used to extract a single digit from a numeric string at a specified position.This filter starts counting positions from the "last digit" of the numeric string, with the position parameter starting from 1.
For example, the product code of our goods isPROD20230815BATCH007we want to extract the last digit of the batch number “7”.
Usage is as follows:
{% set productCode = "PROD20230815BATCH007" %}
{% set lastDigit = productCode|get_digit:1 %}
<p>批次号的最后一位是:{{ lastDigit }}</p>
{% set thirdFromLastDigit = productCode|get_digit:3 %}
<p>批次号的倒数第三位是:{{ thirdFromLastDigit }}</p>
After this code runs,lastDigitit will be7,thirdFromLastDigitit will be0.
It is worth noting that,get_digitThe filter is mainly used to extract individual digit characters. If your product code contains non-digit characters, and the position you try to extract corresponds to a non-digit character, get_digitIt will try to convert it to the corresponding ASCII value and subtract 48, which may not be the result you expect. Therefore,get_digitIt is most suitable to use when it is determined that the target position is a numeric character.
Step 4: More complex scenarios and general methods:sliceFilter
If we need to extract not a single digit but a continuous sequence of digits (such as "007"), or if the product code is mixed with letters and numbers, and we need to extract a specific substring, thensliceThe filter would be a more general choice.
sliceThe filter is used to extract elements at specified positions in strings or arrays. It usesfrom:toformat to define the extraction range, wherefromIs the starting index (counting from 0),toIs the ending index (does not include the character at this index).
Continue with the product codePROD20230815BATCH007as an example:
PCorresponding index 0RCorresponding index 1- …
0(Batch number first digit) corresponds to index 170(Batch number second digit) corresponds to index 187(Batch number third digit) corresponds to index 19
To extract the batch number007It starts from index 17 and ends at index 20 (excluding the character at index 20).
{% set productCode = "PROD20230815BATCH007" %}
{% set batchNumber = productCode|slice:"17:20" %}
<p>提取的完整批次号是:{{ batchNumber }}</p>
After this code runs,batchNumberit will be007.
sliceThe filter is very flexible in handling strings containing mixed characters. As long as you can determine the start and end index positions, you can accurately extract the required substring.
Summary
Through the above steps, we see that the Anqi CMS provides powerful template tags and filters, making it simple and intuitive to extract specific information from complex numeric strings. Whether you are extracting a single number or a continuous segment of numbers, you can choose according to your specific needs.get_digitorsliceFilter. This flexibility greatly enhances the efficiency of content operation, allowing your website to display and manage product data more intelligently.
Common Questions (FAQ)
1. If my product code contains both letters and numbers,get_digitCan the filter still accurately extract the numbers I want?
get_digitThe filter may behave less intuitively when encountering non-numeric characters, as it will try to convert the characters to ASCII values for processing. Therefore, if your product code contains a mix of letters and numbers, and you need to extract digits that may correspond to non-numeric characters, or if you need to extract multiple digits, it is recommended to use a more generalsliceFilter.sliceThe filter will directly cut the substring within the character index range you specify, whether it is a number or a letter, it can be accurately obtained.
2. I want to extract the batch number that is not at a fixed position, but identified by a separator (such as a hyphen “-” ), does the Safe CMS have a way to do this?
Of course! If the batch number is defined by a specific delimiter, you can usesplitThe filter splits the entire string into an array, and then retrieves it based on the position in the array of the batch number. For example, the product code isPROD-2023-007The batch number "007" is the third part, you can do this:
{% set productCodeWithDelimiter = "PROD-2023-007" %}
{% set parts = productCodeWithDelimiter|split:"-" %} {# 拆分成 ["PROD", "2023", "007"] #}
{% set batchNumber = parts[2] %} {# 获取第三部分,索引为2 #}
<p>通过分隔符提取的批次号是:{{ batchNumber }}</p>
3. Extracted numbers (such as inventory quantities) need to perform addition, subtraction, multiplication, and division operations, can they be operated directly in the template?
Yes, AnQi CMS supports basic arithmetic operations in templates. You can useaddfilters for addition, or directly apply+/-/*//operators. For example:
`twig {% set stock = '100' | integer %} {# 先将字符串转换为整数 #} {% set newStock = stock|add:50 %} {# 100 + 50 = 150 #}
The increased stock quantity is: {{ newStock }}
{% set price = “199.99”|