How to define and use temporary variables in AnQiCMS templates to simplify complex data processing?

Calendar 👁️ 61

In AnQiCMS template development, we often encounter situations where we need to handle or reuse complex data.Writing complex logic or data paths repeatedly in templates not only makes the code long and hard to read, but also affects maintenance efficiency.At this point,巧妙地利用临时变量,can make the template code clearer,more concise,and more flexible in data processing.

AnQiCMS's template engine provides a powerful and flexible variable definition mechanism that can help us effectively manage and process page data. It mainly uses{% with %}and{% set %}These tags are used to define and assign temporary variables. Understanding and mastering them will greatly enhance your template development efficiency.

The temporary variable mechanism in AnQiCMS templates

In AnQiCMS template syntax, variable definition and assignment can be considered as 'temporarily storing' data within a specific scope for later use. These two main methods have different focuses:

  • {% with %}Tags:Used primarily to define one or more in the currentwithValid temporary variables within a tag block. One typical application scenario is toincludeIntroduce data passed by the child template, or aggregate frequently used data in a local area.
  • {% set %}Tags:Used to define and assign variables at any position in the current template.It offers greater flexibility, where a variable can be declared anywhere in the template and can be reassigned in subsequent code. This allows{% set %}It is an ideal choice for processing intermediate calculation results, capturing filtered data, or constructing complex data structures in a loop.

Understood the basic differences between these two tags, next we will delve into how they simplify complex data processing through specific application scenarios.

Use{% with %}Define local scope variables

{% with %}Labels allow you to define variables within the scope of a code block. This means that these variables are only available in{% with %}and{% endwith %}the area between

Basic syntax:

{% with 变量名1=值1, 变量名2=值2 %}
    {# 在这里使用定义的变量 #}
    {{ 变量名1 }}
    {{ 变量名2 }}
{% endwith %}

Actual application:

Assuming you have a header area where you need to display the website title and keywords. If you don't want to repeat writing it on each page{% system with name="SiteName" %}and{% tdk with name="Keywords" %}and this header is a sub-templateincludeintroduced,{% with %}it can be put to use.

{# 在父模板中,定义变量并传递给子模板 #}
{% with pageTitle="我的定制标题", pageKeywords="模板,变量,安企CMS" %}
    {% include "partial/header.html" with currentTitle=pageTitle currentKeywords=pageKeywords %}
{% endwith %}

{# partial/header.html 子模板内容 #}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ currentTitle }} - {% system with name="SiteName" %}</title>
    <meta name="keywords" content="{{ currentKeywords }}">
</head>
<body>
    {# ... 页面内容 ... #}
</body>
</html>

In this example,pageTitleandpageKeywordsvariables are only{% with %}Valid inside and passedwithThe keyword is passed toheader.htmlChild template, the child template is thencurrentTitleandcurrentKeywordsTo receive and use these values. This approach avoids variable name conflicts and ensures the local management of data.

Use{% set %}Define and reuse variables

{% set %}Tags provide a more flexible way to define variables, their scope is usually the entire current template file. This means once used{% set %}Defined a variable, it can be accessed and reused anywhere after the label, and can even be reassigned.

Basic syntax:

{% set 变量名 = 值 %}
{# 在这里使用定义的变量 #}
{{ 变量名 }}

Actual application:

{% set %}It is very useful when handling intermediate calculation results, formatting data, or extracting specific values from complex structures.

1. Capture the data after the filter is processed:

Suppose you get the creation time of an article from a document list (usually a timestamp), and you want to display it in a specific format at multiple locations. If you call it every timestampToDateThe filter performs formatting, which may seem repetitive. Use{% set %}The formatted results can be stored for use multiple times after one processing.

{% archiveList archives with type="list" limit="1 %}
    {% for article in archives %}
        {# 格式化创建时间并存储到变量中 #}
        {% set formattedDate = stampToDate(article.CreatedTime, "2006年01月02日") %}

        <p>文章标题: {{ article.Title }}</p>
        <p>发布日期: {{ formattedDate }}</p>
        <p>更新通知: 本文章最后一次发布于 {{ formattedDate }}。</p>
    {% endfor %}
{% endarchiveList %}

here,formattedDateThe variable was calculated only once but was reused twice in the template, greatly simplifying the code and improving efficiency.

2. Extracting specific values from complex data structures:

During processingarchiveListWhen returning a document array, you may only want to retrieve the first article under specific conditions, or you may need to quickly extract a nested attribute from a complex object.

{% archiveList articles with type="list" categoryId="10" flag="c" limit="1" %}
    {% set featuredArticle = articles[0] %} {# 获取满足条件的第一篇文章 #}

    {% if featuredArticle %}
        <div class="featured-section">
            <h3>推荐文章:<a href="{{ featuredArticle.Link }}">{{ featuredArticle.Title }}</a></h3>
            <img src="{{ featuredArticle.Thumb }}" alt="{{ featuredArticle.Title }}">
            <p>{{ featuredArticle.Description|truncatechars:100 }}</p>
        </div>
    {% endif %}
{% endarchiveList %}

By{% set featuredArticle = articles[0] %}We directly query

Related articles

How to iterate over an array or object list in AnQiCMS template and display loop count and remaining quantity?

In website content management, dynamically displaying list data is a basic and crucial function.Whether it is an article list, product display, or user comments, we need to present the data efficiently to the users.How to clearly mark the order of list items or inform the user how much content is left to browse can greatly enhance the user experience and readability of the content.AnQiCMS (AnQiCMS) with its flexible template engine, can help us easily meet these needs.

2025-11-07

How to display or hide content blocks in AnQiCMS templates based on conditions (such as `if` statements)?

In website content operation, we often need to display or hide specific content based on different situations, such as displaying special event information on holidays or showing different operation buttons based on the user's status.AnQiCMS provides a flexible template engine, allowing you to easily implement these dynamic content controls, with the most core tool being the conditional statement - `if`. AnQiCMS template syntax is similar to the popular Django template engine, and it is very easy to get started with.

2025-11-07

How to get and display detailed information of a specific user, such as username, avatar, and level in AnQiCMS template?

In website operation, displaying personalized information to users, such as usernames, avatars, and membership levels, can greatly enhance user experience and website interaction.AnQiCMS as a flexible content management system provides intuitive template tags to help us easily achieve this goal.The AnQiCMS template system has adopted a syntax similar to Django templates, allowing backend data to be called through concise tags.When we want to display detailed information about a specific user

2025-11-07

How to loop to display user group information in AnQiCMS template?

In the website built with AnQiCMS, the user grouping function provides us with powerful content management and user permission division capabilities, whether it is to implement membership content, display different information according to user level, or plan VIP services, user grouping is an indispensable foundation.How to flexibly display these user grouping information on the front-end template of a website, which is a focus for many operators.AnQiCMS uses a template engine syntax similar to Django, which makes template writing intuitive and efficient.When it comes to user group information, the system provides

2025-11-07

How does AnQiCMS template reference other template files (such as `header.html`, `footer.html`) to achieve code reuse?

In website construction and maintenance, how to efficiently manage code and avoid redundant labor is the key to improving development efficiency and ensuring website consistency.For users who build websites using AnQiCMS, its flexible template engine provides a powerful code reuse mechanism, allowing us to easily refer to other template files, such as the common header (header) and footer (footer), thereby achieving modular development.The template design of AnQiCMS borrows the syntax features of the Django template engine

2025-11-07

How to display Markdown formatted article content in AnQiCMS template and render it correctly to HTML?

In a content management system, Markdown has become the preferred writing format for many content creators, it is concise, efficient, and easy to convert to structured HTML.For AnQiCMS users, using Markdown to write articles can not only improve writing efficiency but also better organize content structure.Luckyly, AnQiCMS deeply supports Markdown formatted article content and provides a perfect mechanism to ensure that they are correctly rendered into beautiful HTML pages on the website front-end.### Start

2025-11-07

How to implement the parameter filtering function of the article list in AnQiCMS (such as filtering by custom properties)?

As the content of the website becomes richer, users often hope to find the information they are interested in more accurately, rather than searching for a needle in a haystack of disordered content.For operators, providing flexible article list filtering functions can not only significantly improve user experience but also effectively help users discover more related content, thereby increasing the time spent on the website and interaction.AnQiCMS fully understands this need, through its highly flexible content model and powerful template tag system, making it extremely simple and intuitive to implement the parameter filtering function for the article list.Even if it is a custom attribute

2025-11-07

How to display the comment list of articles in AnQiCMS template and support pagination?

Display article comment list and pagination elegantly in AnQiCMS template Article comments are an important part of website interaction, not only can they enhance user engagement, but also bring richer discussions and value to the website content.For operators, how to clearly and efficiently display these comments on the page and support pagination is the key to improving user experience.AnQiCMS provides a set of intuitive and powerful template tags, allowing you to easily achieve this goal.### Understand AnQiCMS template basics AnQiCMS uses similar

2025-11-07