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

In the template design of AnQi CMS, 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 yet powerful template filters, including those that can randomly retrieve a character or value from a string or array.randomFilter.

Understand and master the use ofrandomThe filter can make our website content more vibrant and fresh, effectively enhancing the user experience.Next, we will discuss in detail 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.It is mainly used to randomly select and return an element from the given string or array (usually referred to as a list or slice in templates).

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 hope to randomly select a part of it for display.

Method one: Split the string into an array of characters

如果你想从一个较长的字符串中随机抽取一个独立的汉字、英文字母或符号,可以先使用 Englishmake_listThe filter converts a string into an array of individual characters, and then appliesrandomFilter.

Example code:

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

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

This code will first convertarticleTitleConverted to["安", "企", "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 a comma, space, pipe, etc.), and you want to randomly select one of the words,splitThe 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 with a space)["高效", "定制", "易扩展", "中小企业", "内容运营", "多站点"],randomThe filter will then randomly select a word from it to display.

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

AnQiCMS template tags, such as getting an article listarchiveList分类列表(categoryList)、friend links(linkList)et al., will return an array (or a list object). Applying to these lists directlyrandoma filter, makes it convenient to randomly select a complete element from it.

Get 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 it through a dot.Syntax to access the specific properties of this object.

Sample code: Randomly recommend an article from the popular articles.

{# 使用 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 firstarchiveListGot 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 itrandomArticle. After that, we can access the article object like a normal one,randomArticleofLink/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 here is similar to article recommendation, randomly select onelinkObject, and display itsTitleandLink.

Randomly obtain values from a static array

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

Example code: Display a preset greeting randomly

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

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

Useful Tips and Considerations

  • The unpredictability of the result:randomThe filter recalculates each time the page is loaded, which means that every time you refresh the page, you might see different random results. This is exactly where its dynamism and charm come from.
  • Null value check: When usingrandomBefore the filter, it is best to first|lengthCheck if a string or array is empty. IfobjIt is an empty string or an empty array,|randomIt may return null values, resulting in the page display not meeting expectations. All examples above includeif obj|length > 0such a judgment.
  • 链式操作:randomFilters can be chained with other filters, such as|split | randomThis combination can realize more complex random selection logic.
  • Performance considerationsAlthoughrandomThe filter itself is very efficient, but if your list is very large (for example, tens of thousands of elements), and you need to perform random selection frequently, you may need to consider at the data level or