How to randomly select an element or character from an array or string in Anqi CMS template?

randomfilter.

Understanding core tools:randomFilter

randomThe filter is a very practical feature in the Anqi CMS template, which can randomly select and output an element or character from an array (list) or string. Whether you want to randomly select one from a preset list of options, or randomly pick a character from a piece of text, randomFilters can easily help you achieve this.

Its basic usage is very intuitive, usually{{ 您的变量 | random }}.

For example, if you have an array containing multiple colors and you want to display a color randomly:

{% set colors = ["红色", "蓝色", "绿色", "黄色", "紫色"] %}
<p>今日幸运色:<span style="color: {{ colors|random }};">{{ colors|random }}</span></p>

Every time the page loads, this code will randomly display one of the following colors: red, blue, green, yellow, purple.

Prepare your data: obtain a random element from an array or string

To use effectivelyrandomThe filter, the key is how to prepare the data you want to randomly select.

1. Obtain from the existing array

If your data is already in the form of an array (list), then you can directly userandomThe filter is the simplest way. This is usually applicable to data lists obtained through tags, such as:

{% archiveList latest_articles with limit="10" %} {# 获取最新的10篇文章列表 #}
    {% set featured_article = latest_articles|random %} {# 从这10篇文章中随机选一篇 #}
    <h3>精选推荐:<a href="{{ featured_article.Link }}">{{ featured_article.Title }}</a></h3>
{% endarchiveList %}

In this code block,latest_articlesIt is an array of article lists,randomThe filter will randomly select one article object from it (featured_article), then you can access its link and title like other article data.

2. Convert a string to an array and then retrieve it.

Sometimes, your data may exist as a single string, such as a comma-separated list of keywords. In this case, you need to convert this string to an array first, and then applyrandomFilter. Anqi CMS template providessplitFilter to complete this task.

Assuming you have stored a slogan in a custom field in the background, separated by a vertical|bar:

{% set slogans_string = "用心创作|高效运营|安全稳定|易于扩展" %}
{% set slogan_list = slogans_string|split:"|" %} {# 使用竖线将字符串分割成数组 #}
<p><b>我们的理念:</b>{{ slogan_list|random }}</p>

So, each time the page refreshes, one will be randomly displayed from these four concepts.

If you want to randomly obtain a single character from a string, you can usemake_listThe filter converts a string to a character array:

{% set greeting = "Hello安企CMS" %}
{% set char_array = greeting|make_list %} {# 将字符串转换为字符数组,每个字/字母是一个元素 #}
<p>随机抽取一个字符:{{ char_array|random }}</p>

This allows you to randomly pick a letter or character from "Hello AnQi CMS".

Example of practical application scenarios

randomThe application scenarios of filters are very extensive, which can greatly enhance the dynamicity and user experience of websites:

  1. Randomly display promotional slogans or catchphrases:Prepare multiple versions of the Slogan, display a different one each time a visitor comes.
  2. Randomly recommended content:From an article in a certain category or tag, randomly select one as \
  3. Randomly display an image or icon:For example, add a random border color to each article thumbnail in the article list, or randomly display a partner's logo at the bottom of the page.
    
    {% set border_colors = ["#FF5733", "#33FF57", "#3357FF", "#FF33F5"] %}
    <img src="{{ article.Thumb }}" alt="{{ article.Title }}" style="border: 2px solid {{ border_colors|random }};">
    
  4. A/B test of a simple variant:Randomly display different text or links for simple effect observation.

Summary

The AnQi CMS template includesrandomThe filter is a simple yet very effective tool that allows you to easily introduce random elements on the page, bringing freshness and surprise to users. By combiningsplitormake_listFilters that allow you to flexibly handle different forms of data and convert them into options for random selection.Make good use of this feature, which will help make your website content more vivid and interesting, thus better attracting and retaining users.


Frequently Asked Questions (FAQ)

Q1: Can I randomly display multiple non-repeating elements?

A1: randomThe filter will only randomly select an element each time it is called.If you need to randomly select multiple non-repeating elements from a list, the Anqi CMS template engine itself does not provide complex random sampling or shuffling the entire list order function.random(This may lead to repetition), or it is more recommended to complete the random selection and deduplication of elements in the backend logic (if secondary development is allowed), and then pass the final result to the template for display.

Q2: Will the result of random selection change each time the page is refreshed?

A2:Yes,randomThe filter is re-executed every time the server processes a page request.This means that each time the user visits or refreshes the page, the filter will make a new random selection.This is the source of its dynamism and fun.

Q3: Besidessplitandmake_listWhat are some filters that can help me process the data for random selection?

A3:exceptsplitSplitting strings by delimiter andmake_listIn addition to converting strings to character arrays, there are also some filters that can assist in data preparation:

  • slice: Can extract a specified part of an array or string, for example{{ my_list|slice:"2:5" }}Get elements from the third to the fifth.
  • join: You can concatenate array elements into a string using a specified delimiter, which is very useful when combining display results after processing random selections.
  • lengthGet the length of an array or string, although it is not directly used for random selection, it is very convenient when you need to make conditional judgments based on the amount of data.