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>版权所有 © {{ 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.