How to define and use variables in AnQiCMS templates to optimize the display and management of content?

Calendar 👁️ 67

In AnQi CMS, flexibly using template variables is the key to optimizing website content display and management efficiency.It not only makes your website content more dynamic, but also greatly improves the maintainability and reusability of the template.This article will delve into how to define and use variables in AnQiCMS templates, as well as how to better present content through these techniques.

Variables: The foundation for bringing content to life

Imagine if every title, every description on a website had to be manually modified, that would be so cumbersome.The introduction of variables is to solve this pain point. In the AnQiCMS template system, variables play a role in dynamically displaying backend data on the front-end page, making the content no longer static text, but an active element that can automatically update according to data changes.

The AnQiCMS template uses a syntax similar to the Django template engine, where the use of variables is intuitive and concise. Any content that needs to be dynamically displayed is usually enclosed in double curly braces{{ }}Among them. For example, if you want to display the title of a document, you will see something like{{ archive.Title }}such writing. Here,archiveusually represents the document object of the current page, whileTitleis an attribute of the document object.

These built-in variables allow you to easily access the current context data, such as the title of the page, description, article content, and even image links. For article detail pages, you can directly accessarchive.Title/archive.Description/archive.CreatedTimeWait to obtain all the information of the document; for the category list page, you can access it throughcategory.Title/category.LinkWait to display the details of the category. This direct access mechanism greatly simplifies the presentation of the content.

Define flexibly, use as needed: the power of custom variables

In addition to directly using the variables provided by the system, AnQiCMS also allows us to define our own variables in the template, thereby achieving more advanced content organization and logical control. This is mainly achieved in two ways: withTags andset.

When we need to declare some temporary variables in a local scope of a template, like aincludefragment that is introduced, withLabels make it very convenient. They provide a clear scope for variables, ensuring that variables are only accessible{% with %}and{% endwith %}valid between. For example, when you want to pass specific title and keywords to a common header template, you can use it like this:

{% with title="这是声明给header使用的title" keywords="这是声明给header使用的keywords" %}
    {% include "partial/header.html" with title=title keywords=keywords only %}
{% endwith %}

here,withThe tag defines.titleandkeywordsTwo local variables, and passed them toheader.htmlTemplate.onlyThe keyword ensuresheader.htmlOnly received these two explicitly passed variables, avoiding unnecessary variable pollution.

AndsetTags are used to define a variable with a broader scope in the current template file. If you need to reuse a calculated result or a specific value at multiple locations in the template,setthe tag would be a better choice:

{% set greeting = "欢迎来到我们的网站" %}
<p>{{ greeting }}</p>

This custom variable capability allows you to preprocess or reorganize data at the template level based on complex business logic without modifying the backend code.

Label联动 with variables: the core of dynamic data

AnQiCMS provides rich template tags for fetching data from the database, such as article lists, category lists, system settings, and so on.These tags, when executed, will assign the queried data to designated variables, and then we can iterate over these variables to display the content.

For example,archiveListLabel used to get the document list. When you use it like this:

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
        <div class="article-item">
            <h2><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
            <p>{{ item.Description|truncatechars:100 }}</p>
            <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
        </div>
    {% empty %}
        <p>暂无文章内容。</p>
    {% endfor %}
{% endarchiveList %}

HerearchivesIt is byarchiveListThe variable assigned by the label, it contains multiple document data. Through{% for item in archives %}The loop assigns the data of a document to a variable each iterationitemThen we can access the details of each document byitem.Link/item.Title/item.Descriptionetc.

Similarly,categoryListTags allow you to traverse the categories of the website,navListTags are used to build complex navigation menus. These tags follow a similar pattern: store the query results in the variable you specify, then traverseforand display in a loop.

Filter: A tool for beautifying and refining variable output

Variables provide the original data, but sometimes we need to format, truncate, or convert the data to better adapt to front-end display.AnQiCMS provides a powerful filter function for this.The filter passes|The symbol can be applied after the variable, allowing for chained calls to achieve multiple data processing.

  • Date and time formatting: The time stored on the backend is usually a timestamp, which is not suitable for direct display to users.stampToDateThe filter can convert it to a readable date format, such as{{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}Let the release time be displayed in the format of "Year-Month-Day Hour:Minute".
  • Text truncation: For the article summary or description, we may need to control the display length to avoid long pages.truncatecharsThe filter can truncate text by character count and add an ellipsis at the end, such as{{ item.Description|truncatechars:100 }}. If the content contains HTML tags,truncatechars_htmlit can maintain the integrity of the HTML structure while truncating.
  • Content Security and Display: When displaying the content entered in a rich text editor (such as an article bodyarchive.Content), to prevent HTML tags from being displayed as plain text by the browser, we need to use|safeA filter that tells the template engine that this content is safe HTML and can be parsed directly. For example:{{ archive.Content|safe }}.
  • Other practical functionsThere are many filters that can help you perform string case conversion(upper,lower,title,capfirst), remove HTML tags(striptags,removetags), URL encoding(urlencodeOperations such as these, together, constitute the powerful processing capability of variable output.

Optimize content display and management: comprehensive application of variables.

By defining, using, and processing the above variables, we can build a highly flexible and easy-to-manage content display.

  • Modular templateUtilizewithandincludeTags, can abstract the common parts of a website (such as headers, footers, sidebars) into independent template fragments and pass the required data through variables.This not only reduces code repetition, but also makes local changes easy.
  • Dynamic content layout: Combined with logical judgment ({% if %})and loop({% for %}),we can dynamically adjust the page layout and content presentation based on different variable values. For example, based on the article'sFlagProperties (Headlines, Recommendations, etc.) display different styles or locations.
  • SEO optimization:tdkTags directly obtain the title, keywords, and description variables of the page, in conjunction withsystem.SiteNameUniform global variables can be used to implement unified and dynamic SEO metadata configuration, improving search engine friendliness. In the static rule of{filename}/{catname}Using variables also makes the URL structure more SEO-friendly.
  • Support for multiple sites and languages: Specify in the tag.siteIdYou can call data from different sites in a template. At the same time,languagesTags allow dynamic switching of language versions,配合 translation tags{% tr %}You can build a true multilingual website.

Mastering the definition and usage of variables in AnQiCMS templates, you will be able to manage content and design templates more efficiently, and ultimately deliver a website that is both beautiful and powerful.


Frequently Asked Questions (FAQ)

Q1: How can I define a variable that can be used globally in a template instead of being limited to a local scope?

A1:In the AnQiCMS template, if you want to define a variable and be able to use it at any subsequent location in the current template (including outside of loops and conditional judgments), it is recommended to use{% set variable_name = "your value" %}This way. For example,{% set page_title = "我们的产品" %}can be used anywhere in the template afterwards

Related articles

How to correctly format timestamps in AnQiCMS templates so that content is displayed as needed?

In the daily operation of website content, time information plays a vital role.No matter the publication date of the article, the launch time of the product, or the latest update of the content, these time points directly affect users' perception and trust in the information.However, in the templates of content management systems, we often encounter dates stored in the form of "timestamps", which are precise but not intuitive.How should we correctly format these timestamps in the AnQiCMS template so that the content can be displayed in the way we expect?

2025-11-07

How to use the (for) loop tag in AnQiCMS template to traverse and display the content list?

Efficiently using the `for` loop tag in AnQiCMS templates to display content lists is an indispensable core skill for building dynamic websites.By flexibly using the `for` loop, we can easily traverse various types of data collections and display them in a customized style on the website page, whether it is a news list, product display, category navigation, or any other repetitive content block, the `for` loop can help you a lot.

2025-11-07

How to use conditional judgment (if/else) tags to control the display logic of content in AnQiCMS templates?

In the development and maintenance of website templates, we often encounter the need to display or hide different content based on specific conditions.This dynamic content display logic is crucial for improving user experience, realizing personalized functions, and optimizing the website structure.AnQiCMS (AnQiCMS) is a powerful content management system that provides a flexible template engine, among which the condition judgment (`if/else`) tags are the core tools to achieve this goal.

2025-11-07

How to implement pagination for document lists in AnQiCMS and support custom page number quantities?

AnQiCMS document list pagination and custom page number settings: Make your content management more efficient Imagine, when your website content becomes rich, with thousands of articles, products, or news lists neatly arranged, if you cannot organize and display them effectively, users may feel at a loss.A good pagination mechanism not only improves user experience and helps visitors quickly find the information they need, but is also an important aspect of SEO optimization.

2025-11-07

How to reuse common code snippets through the `include` tag in AnQiCMS templates to optimize the display structure?

When building and managing websites, improving efficiency and maintaining code neatness is the goal pursued by every operator.AnQiCMS (AnQiCMS) as an efficient content management system, provides powerful template functions, among which the `include` tag is the tool to achieve this goal.It allows us to abstract out repeated code snippets from the website, forming independent modules, and then referencing them where needed, greatly optimizing the template structure and subsequent maintenance work.

2025-11-07

How to implement page layout inheritance and rewriting using the `extends` tag in AnQiCMS templates?

When building a website, maintaining the uniformity of the page style, improving development efficiency, and reducing maintenance costs is the goal pursued by every website operator.AnQiCMS (AnQiCMS) deeply understands this, and its template system design draws on the excellent ideas of the Django template engine, among which the `extends` tag is one of the core functions to achieve this goal. ### The Core Concept of Template Inheritance Imagine you are designing a series of posters.Each poster has a common brand logo, top title, and bottom contact information, with only the promotional content in the middle being different

2025-11-07

How to set the automatic compression and thumbnail processing method in AnQiCMS, which affects the image display on the front end?

The quality of website content is often not just reflected in text, but images as visual elements also play a crucial role.In website operation, how to efficiently handle images, ensuring that the images are clear and beautiful while also considering the loading speed, this is the core value of AnQiCMS image processing function.Today, let's delve deeper into how AnQiCMS helps us manage the automatic compression and thumbnail processing of large images, as well as how these settings will affect the display effect of images on the website's frontend.### Say goodbye to slow image loading

2025-11-07

How to configure the category template and document template in the background of AnQiCMS to achieve personalized content display?

As website operators, we all hope that our website content can be presented to visitors in the most attractive way possible.This is not just about visual beauty, but also about how the content structure can better serve users and how to highlight the unique brand character of the website.AnQiCMS fully understands this need, therefore it provides a powerful and flexible template configuration feature in the background, allowing you to achieve highly personalized displays based on different content types - whether it is articles, products, or category pages.Below, let's learn together how to configure category templates and document templates in the AnQiCMS backend

2025-11-07