How to randomly get a character or value from a string or array?

Calendar 👁️ 75

In AnQi CMS template design, we often encounter the need to dynamically display content, such as randomly recommended articles, randomly displayed product images, or randomly selecting one from a set of preset keywords for display. To achieve this flexible and variable content presentation, AnQi CMS provides simple and powerful template filters, including the ability to randomly obtain a character or value from a string or array.randomfilter.

Understand and masterrandomA filter that can make our website content more vibrant and fresh, effectively enhancing the user experience.Next, we will delve into how to use this practical feature in the AnQiCMS template.

Core function:randomFilter parsing

randomThe filter is a very convenient feature built into the AnQiCMS template engine.Its main function is to randomly select and return an element from a given string or array (usually referred to as a list or slice in the template).

Basic usageVery intuitive:{{ obj|random }}

Among themobjCan be a string variable, or an array variable containing multiple values.When applied to a string, it will randomly return a character from the string;When applied to an array, it will randomly return an element from the array.

Scenario one: Randomly obtain a character or substring from a string

Assuming we have a string containing various information, we want to randomly extract a part of it for display.

Method one: Split the string into an array of characters.

If you want to randomly select an independent Chinese character, English letter, or symbol from a longer string, you can first usemake_listThe filter converts a string into an array of single characters and then applies itrandomfilter.

Example code:

{# 假设我们有一个字符串变量叫做 articleTitle #}
{% set articleTitle = "安企CMS,让内容管理更简单高效!" %}

{# 从字符串中随机获取一个字符 #}
<p>今天为您推荐的幸运字符是:<b>{{ articleTitle|make_list|random }}</b></p>

This code will first convertarticleTitleto["安", "企", "C", "M", "S", ",", "让", "内", "容", "管", "理", "更", "简", "单", "高", "效", "!"]such an array, thenrandomThe filter will randomly select a character from this array and display it.

Method two: Split the string into an array of substrings by delimiter.

If your string is composed of multiple words or phrases connected by a specific delimiter (such as commas, spaces, pipes, etc.), and you want to randomly select one word, thensplitThe filter comes into play.

Example code:

{# 假设有一个关键词字符串 #}
{% set keywords = "高效,定制,易扩展,中小企业,内容运营,多站点" %}

{# 将关键词字符串按逗号和空格拆分为数组,然后随机选择一个 #}
<p>今日关键词推荐:<b>{{ keywords|split:", "|random }}</b></p>

Heresplit:", "Will convert a stringkeywordsSplit into an array using the separator ', '` (comma and space)["高效", "定制", "易扩展", "中小企业", "内容运营", "多站点"],randomThe filter will then randomly select a word from it for display.

Scene two: Randomly retrieve a value from an array (list)

AnQiCMS template tags, such as getting a list of articles (archiveList), category lists(categoryList)友情链接(linkListArrays (or lists) that contain elements such as these will return an array. You can directly apply filters to these lists to conveniently randomly select a complete element.randomFilters, which can be conveniently used to randomly select a complete element from among them.

Retrieve a random object and its properties

WhenrandomWhen a filter is applied to an array of objects, it returns a random object. Then you can access its properties using a dot.How to access the specific properties of this object.

Example code: Randomly recommend a popular article.

{# 使用 archiveList 标签获取最近10篇热门文章,并存入 archives 变量 #}
{% archiveList archives with type="list" order="views desc" limit="10" %} {% endarchiveList %}

{% if archives|length > 0 %}
    {# 从热门文章列表中随机选取一篇 #}
    {% set randomArticle = archives|random %}
    <div class="random-recommendation">
        <h4>随机推荐:</h4>
        <a href="{{ randomArticle.Link }}" title="{{ randomArticle.Title }}">
            {# 访问随机文章的标题和链接等属性 #}
            <img src="{{ randomArticle.Thumb }}" alt="{{ randomArticle.Title }}" class="img-fluid">
            <h5>{{ randomArticle.Title }}</h5>
            <p>{{ randomArticle.Description|truncatechars:50 }}</p>
        </a>
    </div>
{% else %}
    <p>暂无文章可供随机推荐。</p>
{% endif %}

In this code, we first go througharchiveListGot a list of articles and checked if it is empty. If the list is not empty,archives|randomIt will randomly select an article object from this list and assign it torandomArticle. After that, we can access the article object as if it were a normal objectrandomArticleofLink/Title/Thumb/Descriptionsuch properties.

Example code: Randomly display a friend link

{# 获取所有友情链接,并存入 friendLinks 变量 #}
{% linkList friendLinks %} {% endlinkList %}

{% if friendLinks|length > 0 %}
    {# 从友情链接列表中随机选取一个 #}
    {% set randomLink = friendLinks|random %}
    <div class="random-friend-link">
        <p>友情推荐:<a href="{{ randomLink.Link }}" {% if randomLink.Nofollow == 1 %}rel="nofollow"{% endif %} target="_blank">{{ randomLink.Title }}</a></p>
    </div>
{% else %}
    <p>暂无友情链接。</p>
{% endif %}

The logic is similar to article recommendations, randomly select onelinkobject, and display itTitleandLink.

Randomly fetch a value from a static array

Although the strength of AnQiCMS lies in dynamic content management, in some specific scenarios, you may need to define a static array in the template and select randomly from it. At this time, you can uselistfilter.

Example code: Display a random greeting from a preset list

{# 定义一个包含问候语的静态数组 #}
{% set greetings = '["您好!", "欢迎光临!", "很高兴见到您!", "祝您今天愉快!"]'|list %}

{# 从问候语数组中随机选择一个 #}
<p><b>{{ greetings|random }}</b></p>

Practical skills and precautions

  • The unpredictability of the result:randomThe filter recalculates every time the page loads, which means that each time you refresh the page, you may see different random results. This is exactly what makes it dynamic and attractive.
  • Null value check: In userandomBefore the filter, it is best to go through|lengthThe filter checks if a string or array is empty. IfobjThe string or array is empty,|randomMay return null, causing the page display to be inconsistent with expectations. The above examples all includeif obj|length > 0such a judgment
  • Chaining operations:randomFilters can be chained with other filters, such as|split | randomThis combination can realize a more complex random selection logic.
  • Performance consideration: AlthoughrandomThe filter itself is very efficient, but if your list is very large (such as tens of thousands of elements), and you need to frequently perform random sampling, you may need to consider at the data level or

Related articles

How to configure multi-site content display in AnQiCMS

Easily implement multi-site content management and display in AnQiCMS It is a challenge for users who operate multiple brands, sub-sites, or content branches to manage the content of each site uniformly.AnQiCMS provides powerful multi-site management features, allowing you to easily create and maintain multiple independent websites under a single system instance and flexibly control the display of their content.This article will give a detailed introduction on how to configure multiple sites in AnQiCMS and achieve independent management and display of content.### 1. Prepare the work

2025-11-08

In document management, how is the recommended attribute `flag` used to control the display of content on the homepage or other special locations?

In Anqi CMS, the "recommended attribute" (`flag`) is a powerful and flexible feature that allows you to finely control the display of website content on the homepage, category pages, or other specific display areas.Understanding and effectively using this attribute can significantly improve the content operation efficiency and user experience of your website.What is the "recommended attribute" (`flag`) in Anqi CMS?In the Anqi CMS document management module, when you add or edit a document, you will find an option named "recommended properties".These attributes are not traditional classifications or tags

2025-11-08

How to configure independent SEO information and template display for a single page (such as "About Us") in the page management?

In website operation, each page has its unique value and goal.For pages such as "About Us", "Contact Us", and "Terms of Service", they often carry brand stories, core values, or important contact information, which are crucial for building corporate image and user trust.Therefore, configuring exclusive SEO information and personalized display templates for these specific pages is an effective way to enhance the professionalism and user experience of the website.AnQiCMS deeply understands these needs, providing flexible and powerful functions, allowing you to independently configure SEO information and specify personalized template display for each single page

2025-11-08

How to set custom parameters in the background and flexibly call them in the front-end template to display specific information?

In a content management system, flexibility is the key to improving operational efficiency and meeting personalized needs.AnQiCMS deeply understands this, providing powerful custom parameter functions, allowing users to flexibly expand content attributes according to business characteristics, and accurately display this information in front-end templates.This article will discuss in detail how to set custom parameters in the Anqi CMS backend, as well as how to call them in the front-end templates to create a more expressive and functional website.--- ### The Power of Custom Parameters

2025-11-08

How to safely concatenate string and numeric variables in the AnQiCMS template?

During the development of AnQiCMS templates, we often need to combine different text segments, numerical information, and even system variables to form a complete output content, such as building dynamic links, displaying formatted data, or generating user-friendly prompt information.This process involves concatenating strings and numeric variables, and how to safely and efficiently complete this operation is an indispensable aspect of template development.AnQiCMS's powerful template engine provides a variety of flexible mechanisms to support these needs.AnQiCMS template engine syntax is similar to Django

2025-11-08

How to correctly escape special characters in the AnQiCMS template to avoid display errors?

In website content management, we often need to display text containing various special characters.If these special characters are not handled correctly, it may lead to page layout chaos, functional anomalies, and even security vulnerabilities.AnQiCMS provides a powerful mechanism to help us handle these special characters during template rendering, ensuring the correct display of content and the security of the website.

2025-11-08

How to automatically capitalize the first letter of an article title, or to achieve full uppercase/lowercase conversion?

In content operation, a standardized and unified title format is crucial for the brand image of the website and the user reading experience.To enhance visual tidiness or to meet specific design styles, automatically adjusting the case of the article title is a very practical feature.AnQiCMS as a flexible content management system, provides a convenient way to help us achieve this goal without complex programming, and it can be easily handled.

2025-11-08

How to achieve text centering or left-right alignment formatting in templates for AnQiCMS?

In web design, the layout and alignment of content are key elements of user experience.No matter if you want to center the title or align the paragraph text to the left, AnQiCMS provides a flexible template mechanism, combined with standard Web technology, which can easily meet these needs.AnQiCMS as a content management system developed based on the Go language has its core advantages in providing efficient, customizable content management and data output.It uses a syntax similar to the Django template engine, allowing you to combine system data (such as article titles, content, etc.) with

2025-11-08