How to correctly use the double curly braces `{{}}` and percentage signs `{% %}` tags in AnQiCMS templates to control the display logic of content?

Calendar 👁️ 79

When using AnQiCMS to build and manage websites, flexibly using template language is the key to improving efficiency and achieving personalized display. Among them, double curly braces{{}}and the percentage tag{% %}Are two core 'roles' controlling the display logic of the template file.They each have different responsibilities, understanding and using them correctly can help you easily master the powerful template function of AnQiCMS.

I. The "speaker" of content: double curly braces{{}}usefulness

double curly braces{{}}The main function isoutput the content of the variableWhen you need to display variables directly from the background data or defined in templates on a webpage,{{}}They came into use. They are like a megaphone, shouting out the information carried by the variables without any change.

The most common usage is to output the title of the page, article content, or system settings:

<title>{{tdk.Title}}</title>
<h1>{{archive.Title}}</h1>
<img src="{{system.SiteLogo}}" alt="{{system.SiteName}}" />

Here, tdk.Title/archive.Title/system.SiteLogoandsystem.SiteNameAll variables are obtained from the AnQiCMS backend.

What's more powerful is,{{}}Can be used withFilter (Filters)Combine usage to format and process output content. For example, you may need to format dates, truncate long text, or perform case conversions:

<span>发布日期:{{item.CreatedTime | stampToDate("2006-01-02")}}</span>
<p>{{item.Description | truncatechars:100}}</p>
<div>{{item.Title | upper}}</div>
  • stampToDate("2006-01-02")The filter will timestampitem.CreatedTimeFormatted as a string in the format "Year-Month-Day".
  • truncatechars:100The filter will also treatitem.DescriptionTruncated to a maximum of 100 characters and appended with an ellipsis.
  • upperThe filter will transform.item.TitleConvert all letters to uppercase.

It should be noted that, for security reasons,{{}}The default behavior is to automatically escape HTML tags and JavaScript code to prevent cross-site scripting (XSS) attacks. If you are sure that the content of a variable is safe HTML and you want it to be parsed by the browser instead of being displayed as plain text, you can use|safeFilter:

<div>{{archive.Content | safe}}</div>

This is very useful in scenarios such as displaying article details, rich text editor content, etc.

Part two: The 'baton' of logic: percentage tags{% %}of art

and used for content output{{}}Different, percentage tags{% %}主要用于Control the logical flow and behavior of the template.They do not directly output content, but execute a series of instructions, such as conditional judgments, loop traversals, including other template files, or calling various data tags provided by AnQiCMS.{% %}Tags must appear in pairs, that is, there is a starting tag and a corresponding end tag (such as{% if %}corresponding{% endif %})

  1. Conditional judgment:{% if %}Control the display logic of contentWhen you need to decide whether to display a certain piece of content based on specific conditions,{% if %}Tags are your first choice. It supportselif(otherwise if) andelseOtherwise structure makes logical judgment more flexible.

    {% if item.Thumb %}
        <img src="{{item.Thumb}}" alt="{{item.Title}}" />
    {% else %}
        <img src="/static/images/default-thumb.png" alt="无缩略图" />
    {% endif %}
    

    This code judges if.item.ThumbIf the variable exists, display the corresponding thumbnail; otherwise, display a default image.

  2. Loop traversal:{% for %}Dynamically generated listFor list data (such as article lists, category lists, navigation menus),{% for %}The tag can iterate over arrays or collections, generating repeated HTML structures for each element. It can also be combined to handle the case where the list is empty.{% empty %}Combined with, it can handle the case where the list is empty.

    {% archiveList archives with type="page" limit="10" %}
        {% for item in archives %}
        <li>
            <a href="{{item.Link}}">{{item.Title}}</a>
            <span>浏览量:{{item.Views}}</span>
        </li>
        {% empty %}
        <li>目前还没有任何文章发布。</li>
        {% endfor %}
    {% endarchiveList %}
    

    here,archiveListIt is a custom tag of AnQiCMS, used to get a list of articles.{% for item in archives %}Then iterate through the list to generate the link and title of each article. Ifarchivesis empty, then display{% empty %}the content inside.

  3. Custom label: AnQiCMS entry to powerful functionsAnQiCMS provides rich custom tags, allowing you to easily retrieve various data without writing complex database queries. These custom tags are all through{% %}Call it, for example:

    • Get the category list:{% categoryList %}

      {% categoryList categories with moduleId="1" parentId="0" %}
          <ul>
              {% for category in categories %}
                  <li><a href="{{category.Link}}">{{category.Title}}</a></li>
              {% endfor %}
          </ul>
      {% endcategoryList %}
      

      This code will retrieve all top-level categories under the article model (moduleId=1) and loop to display their names and links.

    • Get system configuration:{% system %}

      <p>版权所有:{% system with name="SiteCopyright" %}</p>
      

      Directly get the copyright information configured on the background.

  4. Variable declaration:{% with %}and{% set %}Simplify the templateYou can use temporary variables to store data or simplify expressions in templates{% with %}or{% set %}.

    {% with greeting="你好,世界!" %}
        <p>{{greeting}}</p>
    {% endwith %}
    
    {% set todayDate = now("2006-01-02") %}
    <p>今天是:{{todayDate}}</p>
    
  5. Template organization:{% include %}and{% extends %}Improve maintainabilityTo enhance the reusability and maintainability of the template, AnQiCMS supports the splitting and inheritance of templates.

    • {% include "partial/header.html" %}: Introduce a common template fragment (such as header navigation, footer) into the current template.
    • {% extends 'base.html' %}: Allow you to define a basic layout (skeleton template), other page templates inherit from it and rewrite specific blocks ({% block %}) to build pages, avoiding the need to write a lot of repetitive code.
    <!-- base.html (骨架模板) -->
    <!DOCTYPE html>
    <html>
    <head>
        <title>{% block title %}默认标题{% endblock %}</title>
    </head>
    <body>
        {% include "partial/header.html" %}
        <div id="content">
            {% block content %}
                <!-- 页面内容将在此处插入 -->
            {% endblock %}
        </div>
        {% include "partial/footer.html" %}
    </body>
    </html>
    
    <!-- index.html (继承 base.html) -->
    {% extends 'base.html' %}
    
    {% block title %}首页 - 我的网站{% endblock %}
    
    {% block content %}
        <h1>欢迎来到我的首页!</h1>
        <p>这是首页的专属内容。</p>
    {% endblock %}
    

Rule of thumb for using these tags

Mastering AnQiCMS template tags, in addition to understanding their functions, it is also necessary to pay attention to some general principles:

  1. Strictly distinguish between uppercase and lowercase: AnQiCMS template variables and tag names are case sensitive.item.Titleanditem.titlewill be considered as two different variables.
  2. Tags appear in pairs: All{% %}Tags such as{% if %}/{% for %}/{% with %}end tags should be present accordingly, such as{% endif %}/{% endfor %}/{% endwith %}.
  3. cleaning blank linesBy default, the template engine parses{% %}When a logical tag is used, it may output the whitespace generated by the line containing the tag. To avoid unnecessary blank lines affecting the page layout, you can use the symbol, such as-symbols like{%- if %}or{% endif -%}.
  4. Understand context: Different pages (such as the home page, article detail page, category list page) or different custom tags (such asarchiveList/categoryListWill provide different variable contexts. Ensure that the variable you are accessing in the current context exists.

By deep understanding{{}}and{% %}These core tags allow you to use AnQiCMS more efficiently and flexibly to build and maintain your website template, realizing a rich variety of content display and functions.


Frequently Asked Questions (FAQ)

  1. Why is my{{变量}}output HTML code instead of the parsed content?This is the default security mechanism of AnQiCMS template engine, to prevent XSS attacks, it will automatically escape HTML tags. If you are sure that the HTML content you want to output is safe and you want the browser to parse and render it, you need to use|safea filter. For example:{{ archive.Content | safe }}.

  2. Why am I referencing in the template{{变量}}Sometimes it will display blank instead of the content I expect?This usually has several reasons:

    • Variable name is spelled incorrectlyPlease check if the variable name is consistent with the document or actual data structure, including case sensitivity.
    • The variable does not exist in the current context.Certain variables are only available in specific page types or within the loop of specific custom tags. For example,item.Titleonly{% for item in list %}valid in the loop

Related articles

How to enable Markdown editor in AnQiCMS and display mathematical formulas and flowcharts correctly?

Today, with the increasingly rich content creation, plain text is no longer sufficient to express complex concepts.If complex mathematical formulas in academic articles or clear process diagrams in project management can be presented intuitively on the web, it will undoubtedly greatly enhance the professionalism and user experience of the content.AnQiCMS (AnQiCMS) understands this need, through the built-in Markdown editor and flexible frontend configuration, allowing you to easily implement these advanced content displays.This article will give a detailed introduction on how to enable Markdown editor in AnQiCMS

2025-11-08

How does AnQiCMS call and display data for specific sites based on different site IDs?

AnQiCMS multi-site data call: easily achieve content sharing and linkage display AnQiCMS is a content management system designed specifically for small and medium-sized enterprises and content operation teams, and its multi-site management function is one of its core highlights.In actual operation, we often encounter such needs: the main station needs to display the latest products of various sub-sites, or all sub-sites need to uniformly display the contact information of the company's headquarters, or multiple content platforms hope to aggregate and display articles on a specific theme.In this case, how to efficiently call and display data from a specific site is particularly important

2025-11-08

How to add `hreflang` tags in AnQiCMS template for multilingual pages to optimize SEO?

In today's globalized internet environment, many websites need to provide content for audiences of different languages or regions.To ensure that these multilingual pages can be correctly understood and displayed by search engines, the `hreflang` tag plays a crucial role.It can tell search engines that your website has multiple language versions and which version should be displayed to which user.

2025-11-08

How to implement the link display for multi-language site switching in AnQiCMS?

In today's globalized digital world, multilingual support for websites has become crucial for reaching a wider audience and expanding market boundaries.AnQiCMS (AnQiCMS) fully understands this need, therefore, it takes multilingual support as one of its core features, aiming to help users efficiently build and manage multilingual websites.This article will focus on how to implement the display of language switch links for multi-language sites in AnQiCMS, supplemented by necessary SEO practices, and provide you with a comprehensive guide.

2025-11-08

How to customize the AnQiCMS content model to meet the display needs of different content types (such as articles, products)?

In today's rapidly changing digital world, website content is no longer just simple articles or product introductions.In order to accurately reach users and improve conversion rates, we often need to tailor the display form and data structure of different types of content to meet their needs.AnQiCMS (AnQi content management system) fully understands this, and the flexible content model function it provides is a powerful tool to solve this challenge.

2025-11-08

How to configure the pseudo-static rules in AnQiCMS to optimize the URL structure and improve the display of content in search engines?

The importance of URL structure in a content management system is self-evident.A clear, concise, and meaningful URL not only enhances user experience but is also a key factor in search engine optimization (SEO).In AnQiCMS, by carefully configuring the pseudo-static rules, we can transform those dynamic URLs that may have complex parameters into static forms, thereby allowing the website content to display better in search engines.Understanding URL Rewriting: Why It Is Crucial for Your Website?Imagine, a web page address is `www

2025-11-08

How to filter and display content according to different conditions (category, model, recommendation attributes) for the AnQiCMS document list tag `archiveList`?

When building a website with Anq CMS, flexibly displaying content is the key to achieving excellent user experience and efficient content management.Among them, the `archiveList` tag is undoubtedly the core tool for content display, which helps us filter and present articles, products, or other custom content model data according to various conditions.This article will delve into how the `archiveList` tag accurately filters and displays the content you want based on categories, content models, recommendation attributes, and other conditions.

2025-11-08

How to use AnQiCMS's `archiveDetail` tag to refine the acquisition and display of the detailed content and custom fields of a specified document?

In AnQiCMS, managing and displaying website content, the `archiveDetail` tag is undoubtedly one of the core tools.It allows us to delve into each specific document, whether it is an article, product, or other custom type, thus extracting and presenting its detailed information, even including those custom fields tailored to business needs.Understand and flexibly apply this tag to make our website content more accurate and rich.### `archiveDetail` label's basic and advanced usage When we are on a document detail page

2025-11-08