How to declare and assign variables in AnQiCMS templates for subsequent use?

Calendar 👁️ 60

As an experienced CMS website operator, I am well aware of the importance of template design for website content display and user experience.Using variables in templates is the key to customizing web pages and improving development efficiency.Today, I will elaborate on how to declare and assign variables in the AnQiCMS template, so that you can build and manage your website content more effectively.

AnQiCMS overview of variable declaration and assignment in templates

In AnQiCMS, the template engine uses syntax similar to Django and Blade, which makes variable declaration and usage very intuitive.By declaring variables in the template, you can store temporary data, reuse calculation results, or pass information to other template fragments.{% with ... %}Tags and{% set ... %}Labels, each of which applies to different usage scenarios and scopes. Understanding the differences between these two methods will help you control the template logic and data flow more finely.

Use{% with ... %}Declare local variables with the tag

{% with ... %}The tag allows you to declare temporary variables within a specific block of the template. The scope of these variables is limited to the{% with ... %}and{% endwith %}Between the tags, once out of this range, the variable will no longer be available. This feature of local scope allowswithThe tag is very suitable for scenarios where temporary calculations are needed or a small amount of specific data needs to be passed to nested template fragments.

The syntax for declaring a variable is{% with var_name=value %}, and must be followed by{% endwith %}Label ends. For example, if you want to set a temporary title and keywords for a part of the page, you can do it like this:

{% with pageTitle="我的定制页面标题" pageKeywords="关键词1,关键词2" %}
    <head>
        <title>{{ pageTitle }}</title>
        <meta name="keywords" content="{{ pageKeywords }}">
    </head>
    <body>
        <h1>欢迎来到 {{ pageTitle }}</h1>
    </body>
{% endwith %}
<!-- 在这里,pageTitle 和 pageKeywords 不再可用 -->

withA common and powerful usage of the tag is with{% include ... %}The tag combines. When you need to pass specific variables to an included template file without the template accessing all variables of the parent template, withLabels are especially useful. You can pass multiple variables at the same time, separated by spaces:

{# 假设 partial/header.html 模板需要 title 和 keywords 变量 #}
{% include "partial/header.html" with title="这是声明给header使用的title" keywords="这是声明给header使用的keywords" %}

Inpartial/header.htmlIn them, you can use these variables directly:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
    <meta name="keywords" content="{{ keywords }}">
</head>

Please note that variable names usually follow camelCase notation, with the first letter of each word capitalized, for examplepageTitle. This can improve the readability and consistency of the code

Use{% set ... %}tags to declare global variables

{% set ... %}Tags are used to declare variables in the current template file, whose scope starts from the point of declaration and extends to the end of the template file, including any blocks or loops it contains. This makessetLabels are more suitable for storing data that needs to be accessed or modified in multiple locations in the template, or for performing one-time calculations and reusing the results.

The syntax for declaring a variable is{% set var_name = value %}No need to close the tag. For example, if you need to calculate a complex number or concatenate a string and use it in multiple places in the template,setthe tag would be a better choice:

{# 在模板的顶部声明一个变量,例如当前年份 #}
{% set currentYear = now("2006") %}

<footer>
    <p>版权所有 &copy; {{ currentYear }} 我的公司</p>
</footer>

<aside>
    <p>我们已运营至 {{ currentYear }} 年</p>
</aside>

setThe variable label can be reassigned within its scope.It provides a flexible way to manage dynamic data in templates, especially when dealing with complex template logic.

{% set totalCount = 0 %}
{% for item in archives %}
    {% set totalCount = totalCount + 1 %} {# 在每次循环中更新计数 #}
    <p>{{ item.Title }}</p>
{% endfor %}
<p>文章总数: {{ totalCount }}</p>

The way variables are accessed and **practical**

Regardless of using{% with ... %}Or{% set ... %}Declared variables are accessed through double curly braces in templates{{ variable_name }}Visit its value. Variables can be simple strings, numbers, or even more complex objects (like lists or dictionaries), and you can access them in a way similar to accessing fields in a Go language struct, using.Access the properties of the object, for example{{ item.Title }}.

Choose in the actual template developmentwithOrsetDepends on your needs for variable scope:

  • {% with ... %}Suitable for local and temporary dataWhen you need to use a variable in a specific small block of template code, or need to pass independent data to theincludetemplate fragment, usewithCan avoid variable pollution of the global scope, making the code clearer.
  • {% set ... %}Suitable for global or cross-block data: When you need to reuse a value throughout the entire template file or across multiple different blocks,setTags are a better choice. For example, calculate a website's global statistics, or set the main image URL for a page.

By properly declaring and using variables, you can make the AnQiCMS template more dynamic, maintainable, and efficient.This will greatly enhance your website content management experience and provide visitors with more attractive page displays.


Frequently Asked Questions (FAQ)

1. Why can't I access a variable declared in a template in another template file?

This is likely due to the variable scope limitation. In the AnQiCMS template, the{% with ... %}declared variable is only valid between{% with %}and{% endwith %}the tag pairs. And{% set ... %}The declared variable has a wide scope within the current template file, but by default, it cannot directly cross over to a completely independent another template file (for example, not throughextendsinheritance orincludeThe template).If you need to share data between multiple independent template files,you usually need to pass the data through the AnQiCMS backend logic to each template context,or consider using global configuration variables (such as through{% system ... %}Label to get website settings).

2.{% set ... %}and{% with ... %}Can the variable names of labels be the same? Will they overlap?

Yes, they can have the same variable name, but their behavior depends on their scope and declaration order. If inside a{% with ... %}block using with external{% set ... %}declared variables with the same name,withVariables declared inside will “cover” the external variables with the same name, but only withinwiththe block. OncewithBlock ends, external variables still retain their original values.This is called variable "shadowing" or "covering", which allows you to use common variable names in the local scope without affecting the external logic.

How to define a list or dictionary (map) type variable in AnQiCMS template?

In AnQiCMS template syntax, you can directly use Go language literals to declare variables of list (slice) or map (map) types, although the documentation does not directly givesetorwithHow to create a detailed example of complex data types, but its Django-like features are usually supported. For example, you can try:

{# 声明一个列表 #}
{% set imageList = ["/img/pic1.jpg", "/img/pic2.jpg"] %}
{% for img in imageList %}
    <img src="{{ img }}" alt="图片">
{% endfor %}

{# 声明一个字典 (或 map) #}
{% set contactInfo = {"email": "[email protected]", "phone": "123-456-7890"} %}
<p>邮箱: {{ contactInfo.email }}</p>
<p>电话: {{ contactInfo.phone }}</p>

The actual support may require testing based on the specific template engine implementation of AnQiCMS, but this method of declaring complex data structures is supported in most Django-like template engines.If you encounter problems, you can consider building complex data structures in the backend controller and then passing them directly to the template.

Related articles

How to format a timestamp into a readable date and time in the AnQiCMS template?

As an experienced CMS website operation personnel of an enterprise, I know that every detail of user experience is crucial in content management.Clarity in presenting dates and times often directly affects readers' perception of the timeliness and professionalism of the content.Today, I will give a detailed explanation of how to convert those mysterious timestamps into the readable date and time format that we are accustomed to in the AnQiCMS template.

2025-11-06

How to generate a pagination navigation with page number control in AnQiCMS template?

Hello! As a senior CMS website operator, I fully understand the importance of high-quality content and user experience.Page navigation is an indispensable part of content-based websites, directly affecting the user's browsing experience and the discoverability of content.In AnQiCMS, generating a pagination navigation with page number control is an intuitive and powerful process. Below, I will elaborate on how to implement this feature in the AnQiCMS template.### In AnQiCMS template, generate pagination navigation with page number control In the content management system

2025-11-06

How to display the friend link list of the website in AnQiCMS template?

As an experienced CMS website operation person in the security industry, I fully understand that in website operation, friendship links are not only an embodiment of external resource cooperation, but also an important aspect of SEO optimization and user experience construction.AnQiCMS has always been committed to providing simple and efficient solutions in content management and template integration, and displaying the friend link list is no exception.Now, I will introduce to you how to elegantly display the website's friend link list in the AnQiCMS template.In modern website operation

2025-11-06

How to render and process the message form fields in AnQiCMS template?

As an experienced security CMS website operation personnel, I am very clear about the importance of high-quality content and smooth user experience for attracting and retaining users.The feedback form is an important bridge for website interaction with users, and its correct rendering and processing in the template is directly related to whether users can contact us conveniently and quickly.Below, I will elaborate on how to render and process the comment form fields in the AnQiCMS template.### Location of the comment form template file In AnQiCMS, the comment form usually has a dedicated template file to carry its content

2025-11-06

How to include other template files in AnQiCMS templates (such as public header/footer)?

In the daily operation of AnQiCMS, efficient content management is not only reflected in the background data processing, but also cannot do without flexible front-end template design.For website operators, extracting common parts (such as navigation bars, footers, sidebars, etc.) and managing them independently, and introducing them to each page in a unified way, is the key to improving work efficiency, maintaining website consistency, and simplifying maintenance.AnQiCMS provides a powerful and intuitive template introduction mechanism, making this process effortless.AnQiCMS's template system is based on Go language and has borrowed from

2025-11-06

How to use the `extends` tag in AnQiCMS templates to achieve template inheritance and content rewriting?

In the daily operation of AnQi CMS, we know that high-quality, well-structured website content is the key to attracting and retaining users.This is not only reflected in the words of the article, but also in the overall user experience and maintenance efficiency of the page.AnQi CMS, with its powerful functionality based on the Django template engine syntax, provides us with an efficient template inheritance mechanism, which is exactly what we are going to delve into today - how to use the `extends` tag to achieve template inheritance and content rewriting.

2025-11-06

How to define and use macro functions to create reusable code blocks in AnQiCMS templates?

As an experienced security CMS website operation personnel, I am well aware that the template function of the content management system is crucial for improving website operation efficiency and content display quality.AnQiCMS's powerful Django template engine syntax provides us with flexible content presentation capabilities, and the Macro function feature is an essential tool for code reuse, simplifying template structure, and improving development and maintenance efficiency.During the process of content creation and publishing, we often encounter some repetitive code snippets, such as the display format of article lists and the layout of product cards

2025-11-06

How to cut, replace, or format strings in AnQiCMS templates?

As an experienced CMS website operation personnel in a safety company, I fully understand the importance of content in attracting and retaining users.A powerful and flexible template system that allows us to accurately present content according to different scenarios and user needs.AnQiCMS with its Django template engine syntax, provides us with rich string processing capabilities, whether it is for slicing, replacing, or formatting, it can be easily realized, thus transforming the original data into captivating web content.### AnQiCMS in template string variable acquisition and basic processing in

2025-11-06