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

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