In AnQiCMS content operation practice, we often need to handle various data submitted by users, which may not be simple text or numbers, but structured information containing multiple elements, such as tags of an article, multiple features of a product page, or multiple choices in a questionnaire.Verify such inputs to ensure they meet our expected quantity requirements; it is crucial for improving data quality and user experience.
AnQiCMS template engine provides a very practicalsplitfilter that can help us easily validate this structured user input data at the template level.
Get to knowsplitFilter
In the AnQiCMS template,splitThe filter is a powerful string processing tool. Its main function is to split a string into an array (or can be understood as a list) according to the delimiter you specify.Imagine that the user enters multiple keywords in a text box, separated by commas, such as 'Anqi CMS, template development, SEO optimization'. ThroughsplitA filter can be used to convert the original string into["安企CMS", "模板开发", "SEO优化"]such a data structure, making it convenient for subsequent processing and verification.
If the string does not contain the specified delimiter,splitThe filter will return an array containing only the original string itself, with a length of 1.If the specified delimiter is an empty string, it will split each UTF-8 character (including Chinese characters) in the original string into an element of the array.
How to utilizesplitPerform data validation
Once the original string issplitWe can easily get the length of the array after converting the filter into an array, which is the number of elements the user entered. That issplitThe filter shines in data validation scenarios. For example, if we need the user to provide at least 2 tags and no more than 5, we can use it first.splitSplit the user input label string into an array, get its length, and then make a logical judgment based on this length.
We will look at a specific example to see how to implement this verification in the AnQiCMS template.Assuming we have a form where users need to enter article tags, and we require that the number of tags must be between 2 and 5.
{# 假设 user_input_tags 是从用户输入获取的字符串,例如 "标签1, 标签2, 标签3" #}
{% set raw_tags_string = request.query.tags %} {# 从URL查询参数获取,实际应用中可能来自表单字段 #}
{# 使用 split 过滤器将字符串按逗号切割成数组 #}
{# 注意:这里分隔符是 ",",如果用户输入可能有空格,例如 "标签1, 标签2",
切割后每个元素可能包含前导或尾随空格,后面会提到如何处理。 #}
{% set tags_array = raw_tags_string|split:"," %}
{# 获取切割后的数组长度 #}
{% set tags_count = tags_array|length %}
{# 进行数量验证 #}
{% if tags_count < 2 %}
<p style="color: red;">您至少需要输入2个标签,当前输入了 {{ tags_count }} 个。</p>
{% elif tags_count > 5 %}
<p style="color: red;">您最多只能输入5个标签,当前输入了 {{ tags_count }} 个。</p>
{% else %}
<p style="color: green;">标签数量符合要求:{{ tags_count }} 个。</p>
<h4>已输入的标签:</h4>
<ul>
{% for tag in tags_array %}
{# 针对每个标签,使用 trim 过滤器去除可能存在的首尾空格,提升用户体验 #}
{% if tag|trim|length > 0 %} {# 进一步判断去除空格后是否为空字符串 #}
<li>{{ tag|trim }}</li>
{% endif %}
{% endfor %}
</ul>
{% endif %}
We first use in this template code,setThe tag will wrap the original label string (raw_tags_string) throughsplitAfter filtering, it is assigned totags_arraythe variable. Then, we gettags_arrayoflengththe number of tags.tags_count. Finally, passif/elif/elselogical judgmenttags_countDoes it meet the requirement of 2 to 5, and provide corresponding prompt information.
It is worth mentioning that in the traversaltags_arrayWe used an additional method when outputting each tag.trimFilter (tag|trimThis is because the user may accidentally leave extra spaces when entering, such as "Label1, Label2".
}splitThe filter will only split by the specified delimiter and will not automatically remove these spaces.trimThe filter can effectively remove spaces at the beginning and end of a string, making the display more tidy. We also added atag|trim|length > 0check to avoid creating empty tags when users input",,"this kind of consecutive delimiters.
some considerations in practice
- choice of delimiter: Choose an appropriate delimiter based on the actual user input habits and business needs. Common ones include commas (
,), semicolons (;) or pipe characters (|)et. If there may be spaces between separators and content when the user enters it, then usesplitafter each elementtrimis a good habit. - Empty string processingAs described in the document, if the user enters an empty string (for example, nothing is filled in),
splitthe filter will split it into an array containing an empty string.[""]ItslengthIt remains 1. This means that if your validation logic is "at least 1 valid element", you need to judge each element antrimWhether the length is greater than 0 to filter out invalid empty elements. - Client-side and server-side verification: Although the AnQiCMS template provides powerful data validation capabilities, this is mainly used for immediate friendly user feedback.For strict verification involving data integrity and security, it is still generally recommended to perform it on the backend (server side) to prevent malicious users from bypassing frontend or template verification.
By flexible applicationsplitFilters and other auxiliary filters, we can build a more robust and user-friendly data input validation mechanism in the AnQiCMS template.
Frequently Asked Questions (FAQ)
1.splitFilters andmake_listWhat are the differences between filters?
splitThe filter will split the string based on the specifications you provideseparator(such as commas, spaces, etc.) into an array. Its purpose is to split structured text content. While themake_listfilter will split the string ofEach character(including Chinese characters, letters, numbers, and symbols) is split independently into an element of an array. If you want to split a sentence into words, you should usesplitIf you want to split a word into individual characters,make_listIt is more appropriate.
2. How to ensure that each element entered by the user does not have any extra spaces after splitting?
splitThe filter will only split according to the specified delimiter and will not automatically remove the spaces at both ends of each element. To get clean elements, you need to use each element in the array when traversing it.trima filter. For example:{{ tag_item|trim }}This can remove the whitespace before and after the elements.
**3. If the user leaves the input box blank,splitWhat will the filter return? How should I handle this situation?