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

Calendar 👁️ 61

In AnQi CMS template, adding dynamism and fun to the content is an important aspect of improving user experience.Sometimes, we want to display a random element on the page, such as a random slogan, a random recommendation tag, or randomly select an image from a group of images.The Anqi CMS leverages its flexible Django template engine syntax to provide a simple yet powerful way to meet this requirement, with the most core tool beingrandomfilter.

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.

Related articles

The `count` filter calculates the number of times a keyword appears in an array, is it a partial match or a complete match?

In Anqi CMS template development, the `count` filter is undoubtedly a very practical tool for processing data, which can help us quickly count the frequency of a specific keyword in the data.However, when using this filter, many users may be puzzled: when it handles string and array data of different types, is the keyword matching method 'partial matching' or 'exact matching'?This is crucial for accurately presenting content data.

2025-11-08

How to calculate the number of times a keyword appears in a string or array in the Anqi CMS template?

In content operation, precisely mastering the use of keywords on the page plays a crucial role in SEO strategy, content quality assessment, and user experience optimization.AnQiCMS (AnQiCMS) is a flexible and efficient content management system with a powerful template engine built-in with many practical features, including a filter that can help us easily calculate the number of times keywords appear.Next, we will introduce how to use these features to count the frequency of keywords in the Anqi CMS template.### Deeply understand `count`

2025-11-08

Can the `contain` filter be used to check if a Map (key-value pair) contains a specific key?

AnQiCMS with its efficient and customizable features brings many conveniences to content management.In the daily operation of websites, we often need to dynamically adjust the page content in templates based on the existence of data.Among them, it is a common requirement to judge whether a specific key exists in the data of key-value pair (Map) type.Today, let's delve into whether and how the `contain` filter in AnQiCMS templates can be used to check for the existence of keys in a Map.

2025-11-08

How to determine whether an array or string in an Anqicms template contains a specific keyword?

In AnQi CMS template development, we often need to dynamically display information based on specific attributes or keywords of the content.For example, determine whether an article title contains a certain product name, or check whether a document's tag list contains a hot keyword.This can not only make the website content more targeted, but also improve user experience and SEO effect.The AnQi CMS template engine provides powerful and flexible features to meet these needs.Among them, it is easy to determine whether an array or string contains a specific keyword by using the built-in `contain` filter.

2025-11-08

How to get the first element/character of an array or string in AnQi CMS template?

During the development of website templates, you often encounter the need to extract the first element or character from a data collection (whether it is an array, slice, or string).AnQiCMS uses syntax similar to the Django template engine, providing rich tags (Tags) and filters (Filters), allowing us to flexibly and efficiently handle data.This article will introduce in detail how to use these powerful tools in the AnQiCMS template to easily achieve the operation of getting the first element/character of an array or string.--- ### One

2025-11-08

How to get the last element/character of an array or string in Anqi CMS template?

In Anqi CMS template development, we often encounter the need to obtain the last element or character from a set of data (whether it is an array, list, or string).No matter whether it is to display the latest comments, the last item in the list, or extract the end information of specific text, understanding how to efficiently implement this at the template level will greatly enhance the flexibility and development efficiency of the template.The AnQi CMS template engine provides a simple and powerful filter function that can help us easily achieve this goal.

2025-11-08

How to perform addition operations on numbers in AnQi CMS template, including integers and floating-point numbers?

In AnQiCMS template design, sometimes we need to perform dynamic calculations on the numbers displayed on the page, such as calculating the total price of goods, displaying the cumulative points of users, or adjusting certain values.Whether it is a simple integer addition or involves decimal floating-point arithmetic, AnQiCMS provides intuitive and powerful methods to meet these needs.This article will delve into how to implement addition operations in the AnQiCMS template, making your content display more dynamic and practical.

2025-11-08

How does the `add` filter handle string concatenation operations?

When developing templates with Anqi CMS, we often encounter scenarios where we need to combine text fragments or numbers for display.Whether it is to build dynamic page titles, concatenate URLs, or perform simple numerical calculations on the page, flexible data processing capabilities are crucial.The Anqi CMS template engine provides a very practical tool - the `add` filter, which can help us easily achieve string concatenation and numeric addition operations.What is the `add` filter?

2025-11-08