How to use Django template engine syntax to display variables and logic structures?

Calendar 👁️ 61

AnQiCMS (AnQiCMS) uses a template engine syntax similar to Django in template creation. This design philosophy aims to provide content operators and developers with a powerful and easy-to-use tool, allowing them to more flexibly control the display of website content.By mastering this template syntax, you can easily display dynamic data on the website frontend and control the presentation logic of content based on specific conditions.

The core composition of template syntax: variables and logical structures

The template syntax of Anqi CMS mainly consists of two parts: double curly braces used to display variables{{ }}Comma and single curly brackets and percentage signs used for logical structure processing{% %}.

  • Show variable{{ 变量 }}This is the most common usage, used to directly display data passed from the backend to the frontend on the page. For example, if you want to display the title of the website, you may use it.{{ siteName }}This format. Variable names usually follow camelCase naming conventions, that is, the first letter of each word is capitalized, for examplearchive.Title/category.Link.

  • Logical structure{% 逻辑结构 %}These tags are used to control the rendering process of templates, such as making conditional judgments, looping through data sets, and so on.The values are displayed differently, logical structure tags must appear in pairs, that is, if there is a start tag, there must also be a corresponding end tag.For example, a conditional judgment structure would be{% if 条件 %} ... {% endif %}.

All template files are with.htmlsuffix and stored in/templateUnder the directory, and it is recommended to use UTF-8 encoding to avoid garbled characters. The static resources such as styles, JS scripts, and images used in the template are then placed in/public/static/In the catalog.

Chapter 2: The Flexible Use of Variables: How to Obtain and Display Data

In AnQi CMS, to display specific data, it is usually combined with template tags to obtain data, and then display variable values through double curly bracket syntax.The system is built-in with rich tags, which can conveniently obtain different types of data.

For example, you can usesystemtags to obtain the system configuration information of the website:

{# 使用 system 标签获取网站名称,并存储到变量 siteName 中 #}
{% system siteName with name="SiteName" %}
<div>网站名称:{{ siteName }}</div>

{# 或者直接输出 #}
<div>网站备案号:{% system with name="SiteIcp" %}</div>

Similarly, if you need to display the title of the article detail page, you can directly use it on the document detail pagearchiveDetailTags:

{# 获取当前文章的标题 #}
<h1>{% archiveDetail with name="Title" %}</h1>

{# 获取指定ID文章的链接 #}
{% archiveDetail articleLink with name="Link" id="1" %}
<p>第一篇文章链接:<a href="{{ articleLink }}">点击查看</a></p>

For content like article content that may contain HTML tags, in order to prevent the browser from displaying it as plain text or causing security issues, we usually use in conjunction with|safeFilter to ensure that HTML can be correctly parsed:

{# 显示文章内容,并确保HTML标签被正确解析 #}
{% archiveDetail articleContent with name="Content" %}
<div>{{ articleContent|safe }}</div>

Timestamp data also needs special processing. Anqi CMS providesstampToDateLabel, it can format a 10-digit timestamp into a readable date and time format:

{# 假设 item.CreatedTime 是一个时间戳,将其格式化为“年-月-日 时:分” #}
<span>发布时间:{{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}</span>

3. Implementation of logical structure: control template process

Logical structure tags make the template 'smart', able to adjust the display of the page based on data status or specific conditions.

  • Conditional judgment{% if %}/{% elif %}/{% else %}This is the most basic logical control, used to decide whether to display the content of a certain block based on conditions.

    {% if item.IsCurrent %}
        <li class="active">{{ item.Title }}</li>
    {% elif item.Status == "pending" %}
        <li class="pending">{{ item.Title }}</li>
    {% else %}
        <li>{{ item.Title }}</li>
    {% endif %}
    
  • Loop through{% for %}/{% empty %}When you need to display multiple data in a list or collection,forThe loop is indispensable. It traverses each element in the collection and assigns the current element to the variable you define in each iteration.

    {# 遍历一个文章列表 #}
    {% archiveList archives with type="list" limit="5" %}
        {% for article in archives %}
            <li>
                <a href="{{ article.Link }}">{{ article.Title }}</a>
                <span>浏览量:{{ article.Views }}</span>
            </li>
        {% empty %}
            {# 如果 archives 列表为空,则显示此处的内容 #}
            <li>目前没有文章可供显示。</li>
        {% endfor %}
    {% endarchiveList %}
    

    You can also useforloop.CounterGet the current loop index (starting from 1), orforloop.RevcounterGet the remaining number of loops, which is very useful when adding special styles or logic to list items.

  • Auxiliary label{% include %}/{% extends %}/{% macro %}These tags greatly improve the maintainability and reusability of the template:

    • {% include "路径/文件名.html" %}: Used to insert a template fragment (such as a page header, footer, sidebar) into the current template. You can also usewithThe keyword passes additional variables to the included template oronlyto limit only the specified variables.
    • {% extends "基础模板.html" %}: Implement template inheritance, define a basic skeleton (such as the overall website layout), and then rewrite specific{% block %}areas in the child templates. This makes modifying the overall website layout very efficient.
    • {% macro 宏名称(参数) %} ... {% endmacro %}: Define reusable template functions. Macros can accept parameters and be called anywhere in the template like functions, effectively reducing duplicate code.
  • Define variables{% with %}/{% set %}In templates, temporarily defining variables can help you better organize code and data.withTag requires{% endwith %}End, the variables defined only take effect within its internal.setLabels can be used throughout the scope of the current template.

    {% with greeting="您好", user="安企CMS用户" %}
        <p>{{ greeting }}, {{ user }}!</p>
    {% endwith %}
    
    {% set pageTitle = "我的自定义页面" %}
    <title>{{ pageTitle }}</title>
    

4. Refining data processing: the use of filters

Filters are used to convert or process variable values, the syntax format is{{ 变量 | 过滤器名称:参数 }}. Filters can be used in a chain, with the output of one filter serving as the input to the next.

Some commonly used and practical filters include:

  • |safe: Tell the template engine that the output variable is safe HTML, no escaping is needed, commonly used for article content and other rich text.
  • |truncatechars:10Truncate a string to no more than 10 characters and add an ellipsis (e.g., 'This is a long sentence…')
  • |upper/|lowerConvert a string to uppercase or lowercase.
  • |add:5: Add numbers or concatenate strings.
  • |cut:" ": Remove all specified characters from a string (e.g., remove all spaces).
  • |length: Return the length of a string, array, or map.
  • |floatformat:2: Format a floating-point number to retain a specified number of decimal places.
  • |join:", ": Join array elements into a string with a specified separator.
  • |split:", "Split a string into an array using a specified delimiter.
  • |dumpUsed for debugging, prints the detailed structure and value of variables to help you understand the real appearance of the data.

Having mastered these template syntax and tools, you can fully utilize the powerful functions of Anqi CMS and create something that is both beautiful and

Related articles

How to ensure that AnQiCMS template files are encoded in UTF-8 to avoid garbled page display?

During the process of building a website with AnQiCMS, you may occasionally encounter the situation where the displayed content is garbled, especially Chinese characters.This not only affects the aesthetics and user experience of the website, but may also have a negative impact on search engine optimization (SEO).The problem of garbled characters is usually related to the inconsistent encoding format of template files, and ensuring that AnQiCMS template files are saved in UTF-8 encoding is a key step to solving this problem.Why UTF-8 Encoding is Crucial?

2025-11-08

How should AnQiCMS template files be named and organized to achieve **display effects??

In Anqi CMS, the display effect of the website is closely related to the naming and organization of the template files.A well-planned template structure not only makes the website look neat and beautiful but also greatly improves development efficiency, facilitates later maintenance, and ensures that content is presented in different scenarios. ### The Foundation of Template Files: `/template` Directory and `config.` All visual presentations of Anqi CMS website start from the `/template` directory.This is the home of all template files. Each set of independent templates

2025-11-08

How to use AnQiCMS filter to batch modify specific attribute values in HTML content?

In website content management, we often encounter scenarios where we need to uniformly adjust or batch modify specific attribute values in a large amount of HTML content.For example, you may need to update the height properties of all images, or add specific `rel` attributes to some links, or even adjust the styles of certain tags generated by the rich text editor.AnQiCMS provides flexible tools to meet these needs, among which the batch replacement function is a powerful tool for directly modifying stored content, while the template filter can dynamically transform content at output time, combined, they can efficiently manage and optimize website content

2025-11-08

How to quickly view the original HTML content contained in the variable when debugging the AnQiCMS template?

During the template development process of Anqi CMS, we often need to view the content contained in variables, especially when variables may carry HTML structures. How to quickly and accurately see the original HTML content instead of the parsed or escaped result by the browser is the key to efficient debugging.Anqi CMS uses a template engine syntax similar to Django, providing several powerful tools to help us solve this problem.Understanding Debugging Needs: Why Do We Need to View the Original HTML?

2025-11-08

What page adaptation modes are supported by AnQiCMS templates, and how to select and implement responsive display?

In the multi-screen era, users access websites through various devices, which has become the norm.To ensure that the website can provide a smooth and friendly experience on any device, page adaptation has become an indispensable part of website construction.AnQiCMS (AnQi Content Management System) fully considers this requirement, providing a variety of flexible template adaptation modes to help users easily cope with display challenges on different devices.

2025-11-08

How to modularize the header, footer, and other common parts in a template and reference them on each page to display uniformly?

In website operation, maintaining the consistency and efficient management of the website pages is the key to improving user experience and operational efficiency.For AnQiCMS (AnQiCMS) users, modularizing the header, footer, navigation bar, and other common parts not only ensures consistency in the overall visual style of the website but also greatly simplifies the maintenance and update work in the future.Strong and flexible template system provided by AnqiCMS, allowing you to easily achieve this goal.### Understanding AnQiCMS Template Architecture AnQiCMS template files are usually stored in

2025-11-08

How to customize the display template for specific articles, categories, or single pages to achieve personalized layout?

In website operation, providing exclusive display methods for specific content can significantly improve user experience and content marketing effectiveness.AnQiCMS (AnQiCMS) is well-versed in this field, providing flexible and diverse template customization features, allowing you to easily create a unique personalized layout for articles, categories, or single pages. The AnQi CMS realizes personalized template customization in two main ways: one is to follow specific **template file naming conventions**, the system will automatically identify and apply;Secondly, it is manually specified in the background management interface to use a custom template file.--- ### One

2025-11-08

How to implement conditional (if/else) dynamic display of content and layout in a template?

In website operations and frontend development, we often need to flexibly display content or adjust the page layout according to different situations.This dynamic ability is the core value of the conditional judgment tag (`if/else`) in AnQiCMS templates.The Anqi CMS template engine is simple and powerful, allowing us to set logic on the page like writing program code, making the website content show endless possibilities.### The Dynamic Beauty of AnQi CMS Template

2025-11-08