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 use
randomBefore 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: Although
randomThe 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