As an experienced website operation expert, I have been dealing with AnQiCMS (AnQiCMS) in my daily work for many years, and I deeply understand its efficient and flexible content management features.When using AnQi CMS to build and maintain websites, a core and frequently encountered requirement is how to accurately display dynamic data passed from the backend or controller in the frontend template.Today, let's delve deeply into this topic and help everyone better master the template features of AnQiCMS.

AnQi CMS is known for its backend developed in Go language and syntax similar to Django template engine.This means that when you need to present the processed data from the backend to the user, you can use a direct and powerful way to operate.

Core mechanism: the 'magic' of variables and tags

In AnQiCMS template files, the core of data display lies in two 'magic' elements:VariablesandTags.

1. Variables: Direct data display

When the back-end or controller passes simple data to the front-end template, such as a website name, a description, or a single field in a list, you can use double curly braces{{ }}Enclose the variable name to display its value directly.

For example, if a variable namedsiteNameis passed from the background, and you want to display it in the template, just write it like this:

<h1>欢迎来到 {{ siteName }}!</h1>

If this variable is an object (typically a struct in Go language),structand you want to access one of its properties (fields), you can use the dot operator..Access it, following the camel case naming convention (capitalized first letter). For example, aarchive(document) object, it hasTitleattributes andLinkproperties, you can use them like this:

<a href="{{ archive.Link }}">{{ archive.Title }}</a>

This method is concise and clear, suitable for most scenarios where data values are directly output.

2. Tag: Logical control and complex data acquisition

Except for directly outputting variables, more complex interactions and data acquisition depend on{% %}The labels not only can achieve conditional judgment, loop traversal and other logical control, but also can call the powerful built-in functions of AnQiCMS to obtain specific types of data, such as article lists, category details, system configurations, etc.

Each tag usually needs a start tag{% tag %}And an ending tag.{% endtag %}to define its scope, unless it is a self-closing tag (such as{% system %})

Let's illustrate with several common scenarios:

a. Obtain system configuration or contact information

AnQi CMS providessystemandcontactTags that allow you to easily access the global configuration and contact information of the website without delving into the background code.

For example, display the website filing number and contact phone number:

<p>备案号:{% system with name="SiteIcp" %}</p>
<p>联系电话:{% contact with name="Cellphone" %}</p>

here,with name="..."It is a tag parameter used to specify the specific field to be obtained. If you want to store the data obtained into a temporary variable for multiple use, you can do it like this:

{% system siteIcp with name="SiteIcp" %}
<p>我们的备案号是:{{ siteIcp }}</p>
b. Loop to display list data

Whether it is an article list(archiveList), category lists(categoryList) or friend links(linkList), it needs to beforloop tags to traverse and display.

For example, display the titles and links of the latest 10 articles:

{% archiveList archives with type="list" limit="10" %}
    <ul>
        {% for item in archives %}
            <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
        {% empty %} {# 如果列表为空,则显示此内容 #}
            <li>目前还没有任何文章。</li>
        {% endfor %}
    </ul>
{% endarchiveList %}

In this example,archiveListThe tag assigns the list of articles obtainedarchivesto the variable, thenforLoop througharchiveseachitem.itemSimilarly, it is an object, you can access through:item.Linkanditem.Title.{% empty %}The clause is:forA practical feature of loops, it will automatically display the preset content when the traversed list is empty.

c. Display detailed page data

On the article detail page or single page detail page, it is usually necessary to display the detailed content of the current page.archiveDetailandpageDetailTags are designed for this. On the detail page, in addition to using these tags, you can also directly access top-level variables (such as{{ archive.Title }})to access the fields of the current document, because the controller usually passes the current document object directly to the template.

For example, display the title, content, and publishing time of the article:

<h1>{{ archive.Title }}</h1>
<p>发布时间:{{ stampToDate(archive.CreatedTime, "2006-01-02") }}</p>
<div>{{ archive.Content|safe }}</div>

Here we introduce a special usage:stampToDateIt is a built-in function provided by AnQiCMS, used to format timestamps into readable dates.archive.CreatedTimeinto a readable date.|safethen it is aFilterIt tells the template engine toarchive.Content(Content usually includes HTML) as safe HTML output, rather than escaping, which is crucial for displaying content in rich text editors.

Filter: The 'beautician' and 'processor' of data

Filters are an indispensable tool for processing and transforming data in the template. They use the pipe character|Affects variables, and can format, truncate, escape, and other operations on data before output.

Some commonly used filters include:

  • |safeUsed to output variables containing HTML code to prevent them from being escaped.
  • |truncatechars:100: Truncate string, limit character count, show extra part.....
  • |add:" 后缀": Add string or number.
  • |lower/|upperConvert the string to lowercase or uppercase.
  • |date:"2006-01-02": Format.time.TimeDate type.
  • |dumpThis is a very useful debugging tool that can print out the detailed structure and type of variables, helping you understand the data content during the development process.

For example, if you want to debugarchiveThe structure of the variable can be temporarily added in the template:

<pre>{{ archive|dump }}</pre>

This will be displayed on the pagearchiveThe complete internal structure of the variable, including all fields and their values, is very helpful for troubleshooting.

Flexibly define variables:withwithset

Sometimes you need to create or modify variables inside the template to simplify code or store temporary results.withandsetLabels provide this ability.

{% with ... %}Used to define a local variable within a specific code block, whose scope is limited to{% with %}and{% endwith %}between.

{% with welcomeMessage="您好,欢迎使用安企CMS!" %}
    <p>{{ welcomeMessage }}</p>
{% endwith %}
{# 在此处,welcomeMessage 将不再可用 #}

{% set ... %}You can define variables in the current template file, whose scope covers the entire template file, making it convenient to reuse in different places.

{% set siteFooter = "© 2023 AnQiCMS 版权所有" %}
<footer>{{ siteFooter }}</footer>

Points for attention in practice and **practice**

  1. Case sensitive:The variable names and tag names in AnQiCMS templates are strictly case-sensitive. Please write them correctly according to the document and actual situation, for examplearchive.Titleinstead ofarchive.title.
  2. Make good use of built-in tags:AnQiCMS provides rich built-in tags (such asnavList/breadcrumb/paginationetc.), which are convenient ways to obtain and display data, and can greatly reduce your development workload.
  3. Keep the template tidy:Try to place complex logic (such as data querying, business processing) in the backend controller, and the template is only responsible for data display. UsingincludeThe label modularizes the header, footer, sidebar, and other common parts throughextendsImplementing template inheritance can enhance the maintainability and reusability of the template.
  4. Safety first:When outputting HTML content submitted by users or from untrusted sources, it is imperative to use|safea filter and ensure that the content has been strictly sanitized on the backend to prevent XSS attacks.

Master these core methods and you will be able to handle and display dynamic data with ease in the AnQiCMS template, building a feature-rich and user-friendly website.


Frequently Asked Questions (FAQ)

Q1: I used in the template{{ myVariable }}But the front-end page didn't display anything, why is that? A1:This usually has several reasons. First, please check if the variable name is spelled correctly and pay attention to the case (AnQiCMS template is case-sensitive).Secondly, confirm that the backend controller indeed sendsmyVariableThis data has been passed to the current template. You can try adding in the template{{ myVariable|dump }}Check if the variable exists and its structure. Ifdumpthere is no output, it is very likely that the variable has not been passed in at all.

Q2: How can I make the HTML tags in the article content I retrieved from the database render normally when displayed in the template, as they are all escaped into plain text? A2:This question is because the template engine, for security reasons, defaults to escaping all output content to prevent cross-site scripting (