How to properly define and use variables in the AnQiCMS template?

Calendar 👁️ 63

As an experienced CMS website operation person, I know that high-quality and clear content is the key to attracting and retaining users.In AnQiCMS template development, correctly defining and using variables is the foundation for dynamic content display and enhancing user experience.Below, I will elaborate on how to define and use variables in the AnQiCMS template to help you better control content display.

Basic variables in the AnQiCMS template

In the AnQiCMS template system, variables are carriers of dynamic content, which display the data from the background management system on the front-end page.Understanding variable definition and usage is the first step in efficient template development.

Directly output the variable value

AnQiCMS's template engine supports syntax similar to Django template engine, the basic way to use variables is through double curly braces{{变量}}Directly output the value stored in the variable.When the AnQiCMS system renders a page, it maps the corresponding backend data to the predefined variables in the template based on the context of the current page.

For example, on a document detail page, the system will automatically provide a variable namedarchivewhich contains all the information of the current document. You can directly output the{{archive.Title}}to display the document title.{{archive.Content|safe}}To display the document content, or{{archive.CreatedTime|stampToDate("2006-01-02")}}To format the output of the document creation time. This method is suitable for accessing system predefined variables or variables obtained through tags

UsesetTags define local variables

For the flexibility of the template, AnQiCMS allows developers to define their own local variables within the template. This is usually done by{% set 变量名 = 值 %}Tag implementation.setThe variables defined by the tag are available in the template file it is in until the file is rendered.

A common use case is that you may need to temporarily store the result of a complex calculation or the data returned by a label for repeated use at different locations in the template, to avoid repeated calls or calculations. For example:{% set pageTitle = "AnQiCMS 模板变量指南" %} <h1>{{ pageTitle }}</h1>

UsewithLabel defines a scope variable

withA label provides a variable definition with more scope limitation. It starts with{% with 变量名 = 值 %}and ends with{% endwith %}The variable can be accessed within the enclosed area. This is required when it is necessary to passincludeThe template fragment passing specific parameters is particularly useful, as it can avoid variable pollution of the global environment.

For example, you have a publicheader.htmlTemplate snippet, it needs to display a custom title and keywords. You can use it in the main template like thiswithTags:{% with title="自定义页面标题" keywords="AnQiCMS, 模板, 变量" %} {% include "partial/header.html" only %} {% endwith %}Inheader.htmlin, you can use it directly.{{title}}and{{keywords}}to retrieve these values.onlykeywords ensure only those passing throughwithThe variable is passed so that it can be used in the included template, thereby maintaining the independence of the module.

Data is obtained from the AnQiCMS tag and assigned to a variable.

AnQiCMS provides rich template tags to retrieve various types of data from the background database.These tags not only can directly output data, but more importantly, they allow the query results to be assigned to a custom variable for further processing and display in the template.

Retrieving and using a single value variable

Many tags (such assystem/contact/tdketc.) support assigning the result of retrieving a single field value to a variable. The general syntax is{% 标签名 变量名称 with name="字段名称" %}. If omitted变量名称Labels will directly output the field value.

For example, get the website name and assign it tositeNameVariable:{% system siteName with name="SiteName" %} 您好,欢迎访问 {{ siteName }}!Thus,siteNameThe variable includes the website name set in the background and can be referenced at needed positions. Similarly, to get the contact phone number:{% contact phoneNum with name="Cellphone" %} 联系我们:{{ phoneNum }}

Getting and iterating over list variables

For tags that need to retrieve a set of data (such as article lists, category lists, navigation lists) likearchiveList/categoryList/navListThey will return an array or slice object. At this point, assigning the query result to a variable becomes crucial, as it allows you to useforLoop to traverse these data and display them one by one. The general syntax is{% 标签名 变量名称 with 参数 %}{% for item in 变量名称 %}...{% endfor %}{% end标签名 %}.

For example, get the list of articles and traverse to display:{% archiveList articles with type="list" categoryId="1" limit="5" %} {% for article in articles %} <div> <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3> <p>{{ article.Description }}</p> </div> {% empty %} <p>当前分类下没有文章。</p> {% endfor %} {% endarchiveList %}

In this example,articlesThe variable is assigned the list of articles queried.forthe loop,articleThe variable will hold an article object from the list in each iteration, you can access it througharticle.Link/article.Titleand so on.{% empty %}The tag provides a graceful way to handle the case when the list is empty.

Scope and naming conventions of variables

In AnQiCMS templates, the scope of variables follows certain rules:

  • BysetVariables defined are globally effective in the current template file.
  • BywithVariables are only defined within their{% with %}and{% endwith %}blocks.
  • Variables assigned by labels (such as{% archiveList articles ... %}) are valid between the start and end of the label block.
  • forin the loopitemVariables are only valid within the current loop iteration.

To improve the readability and maintainability of the template, it is recommended to follow the following naming conventions:

  • Variable names should follow CamelCase naming conventions, for exampleSiteName,CreatedTime.
  • Variables assigned to labels should use meaningful, plural names to represent lists, such asarticles,categories,navs, and single objects should use singular forms, such asarticle,category.

Optimize variable output with filters

The AnQiCMS template engine supports using filters to process and format variable outputs. Filters pass|The symbol is connected after the variable name and can be used in series with multiple filters.

Some commonly used filters include:

  • |safe:To prevent HTML content from being escaped, used for outputting articles that contain HTML tags.
  • |stampToDate("格式"):To format a timestamp into a readable date (such as{{item.CreatedTime|stampToDate("2006-01-02")}})
  • |truncatechars:NTruncate a string to a specified number of characters (such as{{item.Description|truncatechars:100}})
  • |default:"默认值": When a variable is empty ornil, output the default value.
  • |length: Get the length of a string, array, or slice.

These filters can help you flexibly control the display effect of front-end content without modifying the backend logic.

Summary

In AnQiCMS templates, variables are an indispensable element for building dynamic and interactive websites. Whether it is to directly access the context variables provided by the system, or to usesetandwithLabeling local and scope variables, or obtaining and assigning data through powerful content labels, understanding these mechanisms and making good use of filters can make your content creation and template development more intuitive, ultimately presenting high-quality and attractive website content to readers.


Frequently Asked Questions (FAQ)

1. Why does the variable I defined not recognize or display as empty in the template?

First, please check that the spelling and case of the variable names are consistent with the definition, AnQiCMS template engine strictly distinguishes between uppercase and lowercase.Next, confirm whether the variable is accessed within the correct scope.{% with %}Defined, it is only valid in the{% with %}block. If it is a list of data obtained from the tag, make sure that it is in{% for %}Use the correct in the loopitemVariable name. If the variable value comes from background data, you also need to check whether the corresponding content has been filled in the background or whether the query conditions are correct, for examplecategoryIdoridWhether it is valid.

2. I need toincludeHow to use only specific variables in the template fragment, not all parent template variables?

You can use{% include "partial/template.html" with var1=value1 var2=value2 only %}Syntax.onlyThe keyword limits the template to access through onlywithExplicitly passing a variable, which will not inherit other variables from the parent template, helps to improve the modularity and reusability of template fragments, and avoid unexpected variable conflicts.

How to handle a variable that may be empty to avoid displaying on the pagenilor blank?

You can use|default:"默认文本"a filter to set a default value for a variable that may be empty. For example,{{ archive.Description|default:"暂无简介" }}Ifarchive.DescriptionEmpty, the page will display "No introduction available". In addition, you can also use{% if 变量 %}logical judgments to control the display of content, for example{% if archive.Thumb %}<img src="{{ archive.Thumb }}" alt="{{ archive.Title }}" />{% else %}<img src="/static/images/default_thumb.png" alt="默认缩略图" />{% endif %}.

Related articles

How should static resources (CSS/JS/images) be stored and referenced in the AnQiCMS template?

As a website manager who is deeply familiar with AnQiCMS operation, I know that proper management of website static resources is crucial for improving user experience and website performance.In AnQiCMS template development and maintenance, reasonably storing and referencing CSS, JavaScript, and images, etc., is the foundation for building an efficient and stable website.Below, I will elaborate on this key link.

2025-11-06

What file extension should AnQiCMS template files use?

As an experienced AnQi CMS website operation personnel, I know that template files play a core role in building a flexible and efficient website.They not only carry the visual presentation of the website, but also serve as a bridge for content and user interaction.For Anqi CMS, understanding the composition and usage specifications of its template files is the foundation for efficient content management and website optimization.According to the official document of Anqi CMS, template files uniformly use the file extension `.html`.

2025-11-06

How to use built-in filters (such as `truncatechars`, `upper`) to process and convert the data format of template variables?

As an experienced AnQiCMS website operation person, I am fully aware of the importance of content in attracting and retaining users.High-quality content not only requires careful creation, but also needs to be presented in an appropriate format and optimized to enhance user experience and readability.AnQi CMS, with its flexible Django template engine syntax, provides us with powerful built-in filter functions, allowing us to easily process and convert the data format of template variables.Next, I will give a detailed introduction on how to use the built-in filter of Anqi CMS

2025-11-06

What are the different roles of the three auxiliary tags `include`, `extends`, and `macro` in template structure organization?

As an experienced CMS website operation personnel of AnQi, I am well aware of the importance of a clear and efficient template structure for content management and website maintenance.In AnQi CMS, the template engine provides various auxiliary tags to help us better organize and reuse template code, among which `include`, `extends`, and `macro` are the three great tools for building a flexible template architecture.They each have different responsibilities, but together they serve to enhance the maintainability and development efficiency of the template.### Modular content reuse

2025-11-06

How to write conditional judgment (if/else) and loop (for) logic tags in AnQiCMS templates?

As a professional who deeply understands the operation of AnQiCMS, I know that template design plays a core role in the presentation of website content.By flexibly using conditional judgment and loop logic, we can transform static template files into dynamic and intelligent content display platforms, thus better meeting user needs and enhancing the interactivity and user experience of the website.This article will discuss in detail how to write conditional judgment (`if/else`) and loop (`for`) logic tags in AnQiCMS templates, helping you create a more expressive website.

2025-11-06

What character encoding format should the AnQiCMS template file follow when editing?

As an experienced website operator who deeply understands the operation of AnQiCMS, I know that the details of content presentation are crucial to user experience.The character encoding of the template file is one of the essential basic links that should not be ignored.Clear and accurately displaying content is the first step to attracting and retaining users. ### AnQiCMS Template File Character Encoding Specification AnQiCMS template files must strictly follow the UTF-8 character encoding format when edited and saved.

2025-11-06

How to create a responsive, code adaptation, or PC+mobile separation template for the AnQiCMS website?

As a website content expert who deeply understands the operation of AnQiCMS, I know that a high-quality template is crucial for the attractiveness and user retention of the website.AnQiCMS provides great flexibility in template design, supporting various modes to meet different business needs and user access habits.Next, I will elaborate on how to create adaptive, code adaptation, or PC + mobile terminal separation templates for the AnQiCMS website.

2025-11-06

How to set up an independent directory structure for the mobile template of AnQiCMS?

As a website operator who is deeply familiar with the operation of AnQiCMS, I know that a flexible and efficient template management mechanism is important for the website, especially in the mobile-first era, providing an independent optimized template experience for mobile devices is the key to attracting and retaining users.AnQiCMS provides powerful support in template design, including setting up a separate directory structure for mobile templates, which allows us to provide customized content display and interactive experience for different devices.

2025-11-06