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 Asecurity CMS to build and maintain a website, a core and frequently encountered requirement is how to accurately display dynamic data passed from the backend or controller in the front-end template.Today, let's delve into this topic in depth to help everyone better master the template features of AnQiCMS.
Auto 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 on the user's side, you can adopt a straightforward and powerful way to operate.
核心机制:变量与标签的“魔法”
在AnQiCMS的模板文件中,数据展示的核心在于两种“魔法”元素:变量(Variables)and标签(Tags).
1. 变量:直接的数据展示
When the backend or controller passes a simple piece of data to the frontend template, such as a website name, a description, or a single field in a list, you can use double curly braces{{ }}Wrap the variable name to directly display its value.
For example, if the background passes a variable namedsiteNameand you want to display it in the template, just write it like this:
<h1>欢迎来到 {{ siteName }}!</h1>
If this variable is an object (usually a struct in Go language),structand you want to access one of its properties (fields), you can use a dot..Access it, following the camelCase naming convention (capitalizing the first letter). For example, aarchive(document) object, it hasTitleproperties andLinkproperties, you can use them like this:
<a href="{{ archive.Link }}">{{ archive.Title }}</a>
This method is concise and clear, suitable for the vast majority of scenarios where data values are directly output.
2. Tag: Logical control and complex data acquisition
Besides directly outputting variables, more complex interactions and data acquisition require{% %}The package label.These tags can not only implement logical controls such as conditional judgment and loop traversal, but also call the powerful built-in functions of AnQiCMS to obtain specific types of data, such as article lists, category details, system configurations, and so on.
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 us illustrate with several common scenarios:
a. Obtain system configuration or contact information
AnQi CMS providessystemandcontactEnglish tags let you easily get 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="..."Is a parameter of the tag, used to specify the specific field to be retrieved. If you want to store the retrieved data into a temporary variable for multiple use, you can do it like this:
{% system siteIcp with name="SiteIcp" %}
<p>我们的备案号是:{{ siteIcp }}</p>
b. English display list data
Whether it is an article list (archiveList分类列表(categoryList) or friend links (linkList), it needs to befortraversed and displayed through the loop tags.
For example, display the latest 10 article titles and links:
{% 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 will assign the article list obtainedarchivesto the variable, thenforto iteratearchiveseach of themitem.itemIt is also an object, you can access its properties byitem.Linkanditem.TitleAccess its properties.{% empty %}The clause isforA practical feature of loops, it will automatically display the preset content when the traversed list is empty.
c. Display detailed page data
In 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 use top-level variables (such as{{ archive.Title }}Access the fields of the current document, as the controller usually passes the current document object directly to the template.
For example, display the article title, content, and publication time:
<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.CreatedTime). It tells the template engine to|safeis anotherFilter (Filter),archive.Content(usually contains HTML content) As safe HTML output, rather than escaping, this is crucial for displaying rich text editor content in English.
Filter: The 'beautician' and 'processor' of data
Filters are an indispensable tool for processing and transforming data in templates. They are processed through the pipeline symbol|Affects variables, and can format, truncate, escape, and other operations on data before output.
Some commonly used filters include:
|safe: Used to output variables containing HTML code to prevent them from being escaped.|truncatechars:100:截取字符串,限制字符数,超出部分显示English....|add:" 后缀":将字符串或数字相加English。|lower/|upper:Convert the string to lowercase or uppercase.|date:"2006-01-02":格式化Englishtime.Time类型的日期English。|dumpThis is a very useful debugging tool, which 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, which 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, which is very helpful for troubleshooting.
Flexible variable definition:withWithset
Sometimes you need to create or modify variables inside the template to simplify the code or store temporary results.withandsetLabels provide this capability.
{% with ... %}Used to define local variables within a specific code block, whose scope is limited to{% with %}and{% endwith %}between.
{% with welcomeMessage="您好,欢迎使用安企CMS!" %}
<p>{{ welcomeMessage }}</p>
{% endwith %}
{# 在此处,welcomeMessage 将不再可用 #}
{% set ... %}It 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>
Matters needing attention in practice with**Practice
- Case sensitive:The variable names and tag names of AnQiCMS templates are strictly case-sensitive. Be sure to write them correctly according to the documentation and actual situation, for example
archive.TitleInsteadarchive.title. - Make good use of built-in tags:AnQiCMS provides rich built-in tags (such as
navList/breadcrumb/pagination), which are convenient ways to obtain and display data, and can greatly reduce your development workload. - Keep the template neat:As much as possible, place complex logic (such as data queries, business processing) in the backend controller, and let the template be responsible for data display. Utilize
includeThe label modularizes common parts such as headers, footers, sidebars, etc., throughextendsTemplate inheritance can enhance the maintainability and reusability of templates. - Safety first:When outputting HTML content submitted by users or from untrusted sources, be sure 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 in the AnQiCMS template with ease, building a feature-rich, user-friendly website.
Common Questions (FAQ)
Q1: I used it in the template{{ myVariable }}, but nothing is displayed on the front-end page, 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).myVariableThis data has been passed to the current template. You can try adding{{ myVariable|dump }}Check if a variable exists and what its structure is. IfdumpThere is no output, it is very likely that this variable has not been passed at all.
Q2: I got a piece of article content containing HTML tags from the database. When displaying in the template, all the HTML tags are escaped to plain text. How can I make them render normally? A2:This question is because the template engine, for security reasons, defaults to escaping all output content to prevent cross-site scripting (XSS) attacks,