How to declare a temporary variable in AnQiCMS template and use it for content display to improve template flexibility?

In the template creation of Anqi CMS, we often need to display various dynamic content.To make the template more flexible and the code more concise, it is crucial to master the use of temporary variables.The template engine of AnQi CMS provides powerful functionality for declaring temporary variables, which helps us better organize and process data, thus improving the efficiency and maintainability of content display.

Understanding the value of temporary variables

Imagine that you need to display processed data at multiple locations on the page, or a piece of data that is repeatedly used in conditional judgments, or data obtained from a tag that needs further processing before it can be presented.If you repeatedly call tags or write complex expressions, the template code will become long and difficult to read.This is where temporary variables come into play.By storing these intermediate results or preprocessed data in temporary variables, we not only make the code clearer, but also improve the execution efficiency of the template, because the data only needs to be processed once.

The template engine of Anqi CMS provides two main ways to declare temporary variables:{% with %}Tags and{% set %}Tags. They have different focuses and are suitable for different scenarios.

Use{% with %}Tag declaration for local variables

{% with %}Labels are used to declare temporary variables within a specific code block, whose scope is limited to{% with %}and{% endwith %}between.This means that the variables you define within this block will not affect variables with the same name outside the block, nor will they pollute the global variables.This is very useful for scenarios where you need to isolate variables and avoid naming conflicts.

You can declare one or more variables at once, separated by spaces, using变量名="值"The form of. For example, if you want to use a custom title and keywords in a local area:

{% with pageTitle="AnQiCMS 模板指南" pageKeywords="临时变量,模板,AnQiCMS" %}
    <header>
        <h1>{{ pageTitle }}</h1>
        <meta name="keywords" content="{{ pageKeywords }}">
    </header>
{% endwith %}
{# 在这里,pageTitle 和 pageKeywords 变量就无法使用了 #}

{% with %}A common use case for tags is to include other template files ({% include %}When. Sometimes, you want to pass some specific data to the template being included, but you do not want the included template to directly access all the variables of the current template. At this time, you canincludeLabel after usingwithKeyword, and optionally addonlyKeyword to limit the passing of variables:

{# 假设 partial/header.html 需要一个 title 变量 #}
{% include "partial/header.html" with title="我的自定义页面标题" only %}

This is,partial/header.htmlThe template can only accesstitleThis variable will not inherit other context data from the main template, thereby improving the modularity and maintainability of the module.

Use{% set %}Declaration of general variables in tags

With{% with %}Tags are different,{% set %}Label declared variables, whose scope is usually the entire template file or the current block.{% block %}This makes{% set %}more suitable for sharing data between different parts of the template.

{% set %}The usage of the label is very intuitive, you can assign a value directly to a variable, or assign the result of an expression or a filter to a variable. For example, we often need to get the first image from the document's image list as a thumbnail, or display the timestamp after formatting:

{# 假设 archive.Images 是一个图片URL数组 #}
{% set firstImage = archive.Images[0] %}
{% if firstImage %}
    <img src="{{ firstImage }}" alt="{{ archive.Title }}">
{% endif %}

{# 格式化文档创建时间 #}
{% set formattedTime = stampToDate(archive.CreatedTime, "2006年01月02日 15:04") %}
<p>发布时间:{{ formattedTime }}</p>

{% set %}The power of the tag lies in its ability to be combined with various tags and filters provided by the security CMS. For example, when you need tocategoryDetailorarchiveDetailWhen fetching a specific field value from a label and performing further processing:

{% categoryDetail currentCategory with name="Id" %}
{% set categoryId = currentCategory %} {# 将标签的输出结果赋给变量 #}

{# 现在可以使用 categoryId 变量进行其他操作,比如获取该分类下的文档列表 #}
{% archiveList articles with categoryId=categoryId limit="5" %}
    {# ... 循环显示文章 ... #}
{% endarchiveList %}

Or, you may need to render rich text content obtained from custom parameters in the background to ensure that the HTML structure is displayed correctly:

{% archiveParams params with sorted=false %}
    {% set introContent = params.introduction.Value %}
    {% if introContent %}
        <div class="intro-block">{{ introContent|render|safe }}</div>
    {% endif %}
{% endarchiveParams %}

HereintroContent|render|safeFirst, through the combination,renderThe filter may convert Markdown format to HTML, and then throughsafeThe filter ensures that HTML code is correctly parsed and displayed by the browser, rather than being output as escaped plain text.

Flexible application of **practice

  1. Define the scope clearly:Understand{% with %}(Local) and{% set %}(Global/Block) scope differences, choose the most suitable tag. For variables used only in a small block, prefer{% with %}While variables need to be shared across the entire template or a main area{% set %}.
  2. Data preprocessing:Store filtered, truncated, or calculated data in variables to avoid redundant logic during display, making the code for the display part more concise.
  3. Improve readability:Break down complex expressions into multiple temporary variables, which can significantly improve the readability of template code.
  4. Avoid overusing:Although temporary variables are very useful, overuse may also lead to overly complex template logic, which is difficult to maintain.In templates, it is recommended to maintain the principle of data display and a small amount of logic, placing more complex business logic on the backend.

By using flexibility{% with %}and{% set %}These two ways of declaring temporary variables will allow you to create more flexible, efficient, and maintainable security CMS templates, thus better controlling the display of website content.


Common Questions and Answers (FAQ)

Q1:{% with %}and{% set %}What is the core difference in the scope of the label?A1:{% with %}The variable declared by the label only exists in{% with %}and{% endwith %}Valid inside a block, it cannot be accessed outside this block. It is mainly used to create temporary, local contexts.{% set %}Label-declared variables, whose scope is within the current template file or the block where it is located{% block %}are valid within the block. They can be used at any position after the declaration until the template parsing is completed.

Q2: Can the output of AnQiCMS tags or the processing result of filters be stored in temporary variables?A2: Yes. Use{% set %}Labels can conveniently label AnQiCMS tags (such as{% system %}or{% categoryDetail %}) output results, or after various filters (such as|stampToDate/|truncatecharsProcessed data, assigned to a temporary variable. This helps in further processing of data or for reuse in templates.

Q3: How to determine if a temporary variable exists or is empty in a template and provide a default value?A3: You can use{% if variableName %}to determine if a variable exists and is not empty. At the same time, the template engine of Anqi CMS provides|defaultand|default_if_noneFilter.{{ variableName|default:"默认值" }}you canvariableNamedisplays the default value when it does not exist or is an empty string, zero value; and{{ variableName|default_if_none:"默认值" }}It is specifically used to judge whether the variable isnil(null pointer), if it is, the default value is displayed, which is particularly useful for handling the back-end data that may be returnednil.