In Anqi CMS template, how does the `random` filter implement the random selection of an element from an array or string to display and enhance the dynamic nature of the content?

Calendar 👁️ 70

Make the Anqi CMS website content vivid: explorerandomFilter, the mystery of dynamic display realization

In this era of information explosion, an efficient and flexible website content management system is an indispensable tool for operators.The Anqiyun CMS, developed based on the Go programming language, is dedicated to providing a high-performance, easy-to-expand content management solution. It uses syntax similar to the Django template engine in template design, greatly simplifying the complexity of development and content presentation.But in addition to content publishing, we all hope that the website can maintain a sense of freshness, so that visitors can gain some new ideas every time they visit, and avoid monotonous static displays.How can you inject dynamic vitality into the website content without increasing additional development costs?Today, let's delve into a very practical and interesting filter in the AnQiCMS template---randomIt can help us easily achieve random display of content.

randomThe filter, as the name suggests, is the core function of randomly selecting and displaying an element from a given data set.This dataset can be a predefined list (or array) that you have set up, or it can be a plain string.Imagine that your website has a set of carefully prepared visitor tips, recommendations, product features, and even daily slogans for the website, and you want to see different content combinations every time a user visits, thenrandomThe filter is exactly for this.

applyrandomFilter, your website can immediately gain multiple advantages. First, it can significantly enhance the content ofdynamicityanduser engagementWhen visitors see different recommendations or tips each time they refresh the page, they feel that the website is more vibrant, thereby extending their stay time and increasing their interest in exploration.Secondly, for content operations, this is a kind ofan efficient and cost-effective carousel mechanismNo need for complex backend logic or database queries, just a simple configuration in the template layer can achieve random switching of elements such as marketing language, selected recommendations, and call to action (CTA).This not only optimizes the user experience, but also provides a convenient way to test the attractiveness of different content without modifying the code.

then, this powerfulrandomHow does the filter work specifically? Its usage is very intuitive, usually in the form of{{ 您的变量 | random }} appearing in the AnQiCMS template.

Let's look at some actual examples:

1. Randomly select an element from the predefined array:

Assume your website needs to display a random quote or prompt in a certain area of the page. You can define an array containing multiple sentences directly in the template and then apply itrandomfilter.

{% set inspirationalQuotes = ["今天,你学习了吗?", "坚持不懈,方能成功!", "安企CMS让建站更简单。", "不要停止探索未知的世界。", "每次进步一点点,就是最大的成功。"] %}
<p><b>每日箴言:</b>{{ inspirationalQuotes|random }}</p>

In this code, we first usesetA tag defined a namedinspirationalQuotesarray. Then, throughinspirationalQuotes|randomEach time the page is loaded, the system will randomly select a sentence from this array to display to visitors. This way, your website can provide a fresh opening every time it is visited.

2. Select a random character from a string:

In most cases, we may prefer to select a complete text block from a list, butrandomThe filter also supports randomly selecting a character from a string. This may come in handy in certain趣味性 or captcha scenarios:

{% set brandName = "AnQiCMS" %}
<p>今天的幸运字符是:{{ brandName|random }}</p>

This code will randomly select a letter from the string "AnQiCMS" (e.g., 'A' or 'Q' etc.) for display.

3. Combine existing data to dynamically generate random content:

In actual operation, you may need to pass througharchiveListIn the document list obtained by the tag, randomly select one as a "Special Recommendation" or "Lucky Article". AlthougharchiveListThe label itself does not have a direct random sort parameter, but you can first get the entire list and then utilizerandomto randomly select one from the filter.

For example, assuming you have already passedarchiveListGot a namelatestArticlesarticle list:

{% archiveList latestArticles with type="list" limit="10" %}
    {# 此处省略文章列表的循环显示,我们关注如何随机选取 #}
{% endarchiveList %}

{% if latestArticles %}
    {% set randomArticle = latestArticles|random %}
    <div class="special-recommendation">
        <h3>今日特别推荐:</h3>
        <a href="{{ randomArticle.Link }}">{{ randomArticle.Title }}</a>
        <p>{{ randomArticle.Description|truncatechars:100 }}</p>
    </div>
{% endif %}

Here, we first get the latest 10 articles, iflatestArticlesit exists, we directly pass the entire list torandomA filter is used to obtain a randomly selected article objectrandomArticleThen, we can display the title, link, and summary of the randomly selected article.

AnQiCMS a concise syntax similar to the Django template engine, making it easy to use and apply features includingrandomfilters and other functions are very easy to get started with and apply

Related articles

How to implement `striptags` and `removetags` filters in Anqicms, one for removing all HTML tags and another for removing specified tags?

In Anqi CMS, we often encounter scenarios where we need to handle HTML tags.To ensure the purity of content, meet display requirements, or ensure safety, it is an important ability to flexibly control HTML tags.AnQiCMS's powerful template engine provides the `striptags` and `removetags` filters, which are very useful and can help us easily remove all HTML tags or only remove specified tags.Next, we will delve into how these two filters work together

2025-11-08

How to use the `yesno` filter to output custom text such as 'Enabled/Disabled/Pending' based on the boolean value or the existence of a field returned by the Anqi CMS backend?

In website operation, we often need to display corresponding text prompts on the front page according to the status of the content, such as whether it is enabled, recommended, or online.Directly outputting the boolean value `true` or `false` returned by the backend may not be intuitive and friendly.The AnQiCMS template engine provides a simple yet powerful tool - the `yesno` filter, which can help us elegantly convert boolean values or field existence states into easily understandable custom text, such as "Enabled/Disabled/Pending"}

2025-11-08

The `addslashes` filter in AnQi CMS, how to escape a string that may contain special characters to safely insert into JS or HTML attribute values?

In the daily operation of Anqi CMS, we often need to display the dynamic content stored in the database on the front end of the website.This content may come from user input, data scraping, or other channels, and it is inevitable that it will contain some special characters.If these special characters are not handled properly and directly inserted into JavaScript code or HTML attribute values, it may cause page layout chaos, functionality failure, and even serious security risks, such as cross-site scripting attacks (XSS).

2025-11-08

How does the `add` filter in the Anqi CMS template implement the mixing of numbers and strings and how to handle type mismatches?

AnQiCMS (AnQiCMS) provides flexible and powerful tools for content creators and website developers with its Django-like template engine syntax.When building dynamic web content, we often need to combine different types of data (such as numbers and strings) together to form the final display effect.At this time, the `add` filter in the Anqi CMS template can come in handy.

2025-11-08

How to use the `first` and `last` filters to quickly get the title of the first or last article in the Anqi CMS article list?

In website operation, we often need to quickly extract some specific information from the article list, such as the homepage may need to display the latest article title, or in some special modules, it is necessary to obtain the title of the first or last entry in the article list.AnQiCMS (AnQiCMS) can easily meet these needs with its flexible template engine and rich filter functions.AnqiCMS's template system draws on the syntax of mainstream template engines like Django

2025-11-08

What are the application scenarios and encoding differences of the `urlencode` and `iriencode` filters in the AnQi CMS template when encoding URL parameters?

In AnQiCMS template development, when handling URL parameters, we often encounter the need to encode them.This is mainly to ensure the legality of the URL, avoid special characters from destroying the URL structure, and correctly transmit data containing non-ASCII characters (such as Chinese).AnQiCMS provides the `urlencode` and `iriencode` filters to help us complete this task, but their application scenarios and encoding differences are not the same.

2025-11-08

How to use the `linebreaks` and `linebreaksbr` filters to convert newline characters in the plain text content entered by an Anqie CMS user into HTML `<p>` or `<br>` tags?

In a content management system, processing plain text content entered by users and displaying it on the web page in the expected format is a common requirement.When the user enters text with line breaks in the back-end editor, the browser does not default to rendering it as HTML line breaks.All content may be squeezed onto one line, causing disordered layout and affecting reading experience.Fortunately, AnQiCMS provides a convenient template filter to solve this problem.

2025-11-08

How to automatically add line numbers to code blocks or list content in `linenumbers` filter in Anqie CMS to enhance readability?

In daily content creation and website operations, we often need to insert code examples, configuration lists, or detailed operation steps in articles.The characteristic of this content is that it is multi-line text, and if line numbers can be automatically added to it, it will greatly enhance the reader's reading experience and the professionalism of the content.Imagine when you need to explain a part of the code to the reader, or guide them to complete a complex setup, you can accurately mention 'See line 5 of the code' or 'In step 3', this improvement in communication efficiency is self-evident.

2025-11-08