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 process or reuse complex data.Writing complex logic or data paths directly in the template not only makes the code long and difficult to read, but also affects the maintenance efficiency.At this time, cleverly using temporary variables can make template code clearer and more concise, and data processing more flexible.

The template engine of AnQiCMS provides a powerful and flexible variable definition mechanism, which helps us effectively manage and process page data. It mainly{% with %}and{% set %}These tags are used to define and assign temporary variables. Understanding and mastering them will greatly enhance your template development efficiency.

AnQiCMS Template Temporary Variable Mechanism

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

  • {% with %}Tags:主要用于定义一个或多个在当前 Englishwith标签块内有效的临时变量。它的一个典型应用场景是向 EnglishincludeThe data passed from the included sub-template, or the data that needs to be frequently used in a local area.
  • {% set %}Tags:Used to define and assign variables at any position in the current template.It has broader flexibility, where you can declare a variable anywhere in the template and can reassign it in subsequent code.{% set %}It is an ideal choice for handling intermediate calculation results, capturing data after filter processing, or building complex data structures in loops.

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

Use{% with %}Define local scope variables

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

Basic syntax:

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

Actual application:

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

{# 在父模板中,定义变量并传递给子模板 #}
{% 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{% with %}valid within a block, and are passed towitha subtemplate, where subtemplates areheader.htmlthencurrentTitleandcurrentKeywordsThe name to 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, and their scope is typically the entire current template file. This means that once used{% set %}Defined a variable, it can be accessed and reused anywhere after this label, and even be reassigned.

Basic syntax:

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

Actual application:

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

1. Captured data after filter processing:

Assuming you have obtained the creation time of an article from a document list (usually a timestamp) and you want to display it at multiple locations in a specific format. If you call it each timestampToDateFilter formatting may appear repetitive. Use{% set %}You can save the formatted results and use them multiple times.

{% 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 is calculated only once, but is reused twice in the template, which greatly simplifies the code and improves efficiency.

2. Extracting specific values from complex data structures:

in processingarchiveListWhen returning the document array, you may only want to get 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 %}

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