The `random` filter: How to randomly select a character or element from a string or array?

Calendar 👁️ 70

In Anqi CMS template design, we often need to make the website content dynamic and random to avoid the content from being too static and to increase the browsing interest of users. When you want to display a random option, text, or data from a series of predefined choices,randomA filter is a very practical tool. It can help you easily randomly select a character or element from a string or array (also known as a list or set), adding an unpredictable vitality to your website content.

randomFilter: Injects random vitality into your website content

randomThe core function of the filter is very intuitive: it randomly selects a value from the dataset you provide and outputs it. Whether you want to randomly select a character from a long string or randomly pick an element from a list containing multiple elements,randomFilters can complete this task in an extremely concise manner. It is particularly suitable for scenarios where diversity, personalization, or avoiding repetition of content is needed.

Its uses are varied, for example:

  • Display a random maxim or quotation:Display a different quote or company philosophy each time the page is refreshed in the website's sidebar or footer.
  • Content recommendation:Recommend a random article, product, or service from the same category to increase exposure opportunities.
  • Personalized greeting:Randomly display a greeting based on different times or user actions to enhance the user experience.
  • Dynamic page elements:Randomly change a small icon, background color, or animation effect on the page to make it look more lively and vibrant.

How to userandomFilter

randomThe usage of the filter is very simple, following the standard syntax of the AnQiCMS template engine:{{ 变量 | random }}.

1. Randomly select a character from the string:

When you are going torandomThe filter applies to a string, it will randomly select a character from all the characters of the string.

{# 从字符串 "安企CMS真好用" 中随机抽取一个字符 #}
<p>今天随机抽取到的字是:{{ "安企CMS真好用"|random }}</p>

At each page load, you may see any of the characters “安”、“企”、“C”、“M”、“S”、“真”、“好”、“用”.

2. Randomly select an element from an array or list:

This might berandomA more common application scenario for the filter. If you have an array or list containing multiple elements,randomThe filter can randomly select an element from it.

Assuming you have a set of predefined options, you can first convert them into an array and then randomly select from it. In the AnQiCMS template, you can usesplitThe filter converts a comma-separated string into an array:

{# 将字符串“选项A,选项B,选项C,选项D”按逗号分割成数组,然后随机抽取一个 #}
{% set options = "选项A,选项B,选项C,选项D"|split:"," %}
<p>今天为您推荐的是:{{ options|random }}</p>

This will randomly display one of the options A, B, C, or D each time the page is refreshed.

If your variable itself is an array (such as, through other tags likearchiveListthe data obtained), you can use it directlyrandomFilter:

{# 假设 archives 变量是一个文档列表,随机抽取其中一篇文档的标题 #}
{% archiveList archives with type="list" limit="10" %}
    {% set random_archive = archives|random %}
    <p>随机推荐文章:<a href="{{ random_archive.Link }}">{{ random_archive.Title }}</a></p>
{% endarchiveList %}

Precautions for use

While usingrandomWhen filtering, there are a few details to pay attention to to ensure it works as expected:

  • Handling empty input:IfrandomThe input of the filter is an empty string or an empty array, it will not output any content. Therefore, in some cases, you may need to cooperate withifCheck if a variable is empty or usedefaultSet a default value for the filter.
  • Non-collection type:If you are going torandomThe filter is applied to a single non-collection value (such as a number), it will return the value itself. For example,{{ 5|random }}The output is5not within a certain range of random numbers.randomThe filter is designed to extract fromsetselected from, rather than generated randomly.
  • Dynamics: randomThe filter will be re-randomized every time the page is loaded.This means that every time a user visits or refreshes the page, they may see different random content, which is exactly what brings the dynamic charm to the content.

By flexible applicationrandomFilter, you can add more interactivity and fun to your AnQiCMS website, making content display more vivid and attracting users to pay continuous attention.


Frequently Asked Questions (FAQ)

Q1:randomCan the filter directly generate a random number within a specified range?A1:randomThe filter cannot directly generate random numbers within the specified range.It is designed to randomly select one from an existing collection (such as the characters of a string, the elements of an array).If you need to generate a random number within a range, you usually need to process it in the backend logic and pass it to the template, or create an array containing all possible numbers in the template first and then randomly select one from it.

Q2: If I want to randomly select multiple non-repeating elements from a list,randomCan the filter achieve this?A2:randomThe filter can only randomly select one element at a time. If you need to select multiple non-repeating elements, you can onlyrandomThe filter cannot be implemented directly. This usually requires more complex template logic, such as multiple extractions and recording of extracted elements within a loop, or passing multiple random elements as a list to the template after backend processing.

Q3: If my list or string contains duplicate elements, randomDoes the filter ignore duplicate items when extracting?A3: No.randomThe filter treats each element in the collection equally, even if they are duplicates. For example, if your list is["苹果", "香蕉", "苹果"]So the probability of drawing 'Apple' will be twice that of 'Banana'. It simply selects one randomly from all available options without duplicates.

Related articles

`repeat` filter: How to repeat a specified string N times to generate placeholder content?

In the world of AnQi CMS templates, we often need some flexible tools to quickly build page layouts or generate placeholder content when there is no actual data.The `repeat` filter is a feature that is not very noticeable but very practical, and it can help you output the specified string N times in a concise way. ### `repeat` filter: A practical technique for quickly generating repeated strings In website content management and template design, we often need to display a character, phrase, or even a short segment of HTML code repeatedly.For example, when you need a separator line

2025-11-08

The `urlize` and `urlizetrunc` filters: How to handle the display and truncation of long URLs?

In website content operation, we often need to handle various links, whether it is external resources cited in articles or websites left by users in comment sections.However, when these links are too long, they may not only destroy the overall layout of the page, affect its aesthetics, but may also reduce the reading experience of users.Luckyly, AnQiCMS provides a pair of very practical filters—`urlize` and `urlizetrunc`, which can help us manage and display these long or unformatted URLs gracefully.

2025-11-08

How to automatically recognize URLs in AnQiCMS templates and convert them into clickable hyperlinks?

In website operation, the flexibility of content display and user experience is crucial.We often need to display some external links or references in the content of articles, product descriptions, or various text areas.Manually adding the HTML `<a>` tag to each URL is not only inefficient but also prone to errors, especially when the amount of website content is large or needs to be updated frequently, which is undoubtedly a cumbersome task.AnQiCMS provides an elegant and efficient solution to this pain point.

2025-11-08

`removetags` and `striptags` filters: What is the difference and **choice** when clearing HTML tags?

When managing and presenting content in Anqi CMS, we often encounter a common need: how to elegantly handle HTML tags contained in the content.In order to display a concise summary on the article list page, provide clean meta descriptions for search engine optimization (SEO), or simply to avoid unnecessary style conflicts, removing or filtering HTML tags is a basic and important skill.Aqie CMS provides two powerful filters: `removetags` and `striptags`.

2025-11-08

The `wordwrap` filter: how to elegantly handle the automatic line break display of long text without truncating words?

In website content display, we often encounter layout problems with long text content.When a piece of text is too long and exceeds the container width, if it is not properly handled, it may cause layout disorder and a decline in reading experience.AnQiCMS (AnQiCMS) provides a very practical template filter - `wordwrap`, which helps us elegantly solve the automatic line break display of long text, and the key point is that it maintains the integrity of words, avoids cutting words in the middle, thereby greatly enhancing the professionalism and readability of the content.

2025-11-08

How to implement the unified or independent display of multi-site content on the AnQiCMS front end?

For users with multiple websites, brands, or content branches, how to efficiently manage and flexibly display content has always been a core challenge in website operations.AnQiCMS is a content management system designed for multi-site management, which not only provides a unified backend management interface, but also gives users great freedom in front-end content display, allowing for completely independent content display and easy unified calling and aggregation display across sites.Next, we will delve into how AnQiCMS implements these two seemingly opposing yet complementary content display strategies.

2025-11-08

How to flexibly control the display of website front-end content using a custom content model?

In website content operation, the way content is presented is the key to attracting users, conveying information, and achieving business goals.AnQiCMS (AnQiCMS) provides a highly flexible custom content model, which is a powerful tool for us to finely control the display of website front-end content.It is not just the background data management, but also the cornerstone of the front-end visual and functional experience. ### The Foundation Role of Flexible Content Models One of the core advantages of Anqi CMS is its "flexible content model" feature.In simple terms, a content model is a predefined structural framework for different types of content.

2025-11-08

How does AnQiCMS ensure that users of different languages see the correct content display in its multilingual support feature?

In an increasingly globalized digital world, whether a website can provide a smooth and accurate experience for users of different languages has become a key factor in measuring its success or failure.AnQiCMS (AnQiCMS) knows this and has integrated powerful multilingual support into its design, ensuring that your website content can accurately reach global users.How does AnQiCMS ensure that users of different languages see the correct content display?This is not a one-step solution, but a comprehensive solution from the system level to content management, to front-end display and search engine optimization.

2025-11-08