How to use Django template engine syntax in GoLang to control content display logic in AnQiCMS template?

AnQiCMS as an efficient content management system developed based on Go language, its template system adopts syntax similar to Django's template engine, which is undoubtedly an advantage for those familiar with web development to quickly get started and implement powerful content display logic.It allows us to flexibly control the presentation of content directly at the template level without writing complex backend code.

To understand how to use this GoLang implementation of the Django template engine syntax in AnQiCMS templates to control content display logic, we can break it down into several core parts: variable display, logical judgment, data traversal, code reuse, and data formatting and processing.

The display of variables: direct presentation of content

The most basic template operation is to display data. In AnQiCMS templates, we use double curly braces{{ 变量名 }}Output the value of the variable. These variables are usually data passed from the backend to the template, such as article titles, category names, system configurations, etc.

For example, if we want to display the article title of the current page, we can write it like this:<h1>{{ archive.Title }}</h1>Here are thearchive.TitleThis is the title attribute of the article object passed from the backend. This intuitive syntax allows us to easily embed data into the HTML structure.

Control flow: Implement logical judgment

The display of website content often requires judgment based on specific conditions.For example, only show the image when the article has a thumbnail, or display different content based on the user's login status.if/elif(else if) andelseLabel it to handle such logic.

The basic structure is as follows:

{% if 条件 %}
    <!-- 条件为真时显示的内容 -->
{% elif 其他条件 %}
    <!-- 第一个条件为假,此条件为真时显示的内容 -->
{% else %}
    <!-- 所有条件都为假时显示的内容 -->
{% endif %}

For example, we want to determine if there is a thumbnail on the article detail page and display it:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% else %}
    <p>暂无缩略图</p>
{% endif %}

This structure allows us to make flexible judgments based on the existence or absence of data, the magnitude of the numbers, and the boolean status, thus presenting differentiated content.

Traverse data: Display list content

网站上大量的列表内容,如文章列表、产品列表、导航菜单等,都需要模板系统能够遍历数据集合。AnQiCMS模板使用 EnglishforLoop labels can be used to handle such requirements.

forThe basic syntax of the loop is{% for item in 集合 %} ... {% endfor %}In the loop,itemThe variable will represent each element in the collection in turn, and we can access its data byitem.属性accessing it.

An common application scenario is to display the latest article list:

{% archiveList articles with type="list" limit="5" %}
    <ul>
        {% for article in articles %}
            <li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
        {% empty %}
            <li>暂无文章</li>
        {% endfor %}
    </ul>
{% endarchiveList %}

Here,{% archiveList ... %}It is a special tag provided by AnQiCMS for retrieving article lists.{% empty %}Tags inforThe data collection is empty when executing the loop, which is very suitable for handling user prompts when there is no data. In addition,forLoops also provideforloop.Counter(current loop count) andforloop.RevcounterVariables such as (remaining loop count), etc., make it easier for us to control with greater precision, such as adding special styles to the first article.

Template reuse: Improving development efficiency

When building a website, many page elements are common, such as headers, footers, sidebars, etc. AnQiCMS templates provideincludeandextendsTwo mechanisms are used to achieve template reuse, greatly improving development efficiency and the convenience of later maintenance.

  • includeTags:Used to embed a template file into another template file.This applies to reusable components on the page, such as header navigation, sidebar ads, copyright information, and so on.

    {% include "partial/header.html" %}
    <div class="main-content">
        <!-- 页面主体内容 -->
    </div>
    {% include "partial/footer.html" %}
    

    includeIt can also be done throughwithpassing additional variables and usingonlyLimit the range of variables, increase flexibility.

  • extendsTags:Used to implement template inheritance. We can define a basic layout (base.html), containing the overall structure, common styles, and scripts of the website, andblockThe label definition can be overwritten (overridden) by a sub-template. For example, inbase.htmldefine a content block:

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <title>{% block title %}默认标题{% endblock %}</title>
        <!-- 其他公共head内容 -->
    </head>
    <body>
        <header><!-- 页眉内容 --></header>
        <main>{% block content %}{% endblock %}</main>
        <footer><!-- 页脚内容 --></footer>
    </body>
    </html>
    

    Sub-templates only need to declare{% extends "base.html" %}and then through{% block block_name %}overwrite the corresponding area:

    {% extends "base.html" %}
    {% block title %}我的文章 - AnQiCMS{% endblock %}
    {% block content %}
        <h1>欢迎阅读我的文章</h1>
        <!-- 具体文章内容 -->
    {% endblock %}
    

    This method ensures the consistency of the overall style of the website, while allowing each page to have its unique content.

Filter: Format and process data

Filters are important tools in template language for handling variable output. They allow us to modify, format, or convert the data before displaying it. Filters use the pipe symbol|After connecting to a variable, multiple filters can be used in a chain.

For example,{{ 变量名|过滤器名称:参数 }}.

  • safe:Used to output unescaped HTML content. It is very critical when displaying the article body (usually containing HTML format) to prevent HTML tags from being displayed as plain text.<div>{{ archive.Content|safe }}</div>
  • stampToDate:Convert timestamps to readable date formats. This is a unique utility feature of AnQiCMS, as it directly handles timestamps.<span>发布日期:{{ stampToDate(archive.CreatedTime, "2006-01-02 15:04") }}</span>Here are the"2006-01-02 15:04"Is a date and time formatting reference value unique to the Go language.
  • truncatechars:N:Truncates a string to N characters in length and adds an ellipsis at the end. Often used to display article summaries.{{ article.Description|truncatechars:100 }}
  • add:Perform addition operations or concatenation on numbers or strings.{{ item.Views|add:" 次浏览" }}
  • lower/upper:Convert a string to lowercase/uppercase.

The filter greatly enhances the ability to process data in templates, making the front-end display more flexible and accurate.

AnQiCMS dedicated tag: Deeply integrated with content data

In addition to the general syntax of Django template engine implemented in GoLang, AnQiCMS also provides many specialized content tags, which are closely integrated with the CMS backend data. These tags are used to directly access various types of content data, further simplifying template development.

  • archiveList/archiveDetail:Used to retrieve the list of articles or the details of a single article. It can be filtered by various conditions such as category ID, module ID, recommendation attributes, sorting method, etc.{% archiveList latestArticles with categoryId="1" limit="10" order="CreatedTime desc" %}
  • categoryList/categoryDetail:Used to get the list of categories or details of a single category, and also supports filtering by module ID and parent ID.{% categoryList subCategories with parentId=currentCategory.Id %}
  • pageList/pageDetail:Used to get the list or details of a single page.
  • navList:Used to get the website navigation menu.
  • system/contact/tdk:Used to get system configuration, contact information, and the SEO (TDK) information of the page.

These built-in tags enable us to gain in-depth knowledge of the database structure without needing to delve into it, as we can simply configure the parameters and call the required data in the template, which greatly enhances the efficiency of content operation.

In summary, the AnQiCMS template system, implemented through GoLang and using Django template engine syntax, provides powerful and flexible content display logic control capabilities for our website operators. From basic variable output, to complex conditional judgments and data loops, to efficient code reuse mechanisms, as well as practical data formatting filters and dedicated tags deeply integrated with CMS, all of which make the presentation of front-end content