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

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 %}.