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

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