In Anqi CMS, flexibly using template variables is the key to optimizing the display and management efficiency of website content.It not only makes your website content more dynamic, but also greatly enhances the maintainability and reusability of the template.This article will delve into how to define and use variables in AnQiCMS templates, as well as how to present content better using these techniques.
Variables: the cornerstone for bringing content to life
Imagine how cumbersome it would be if every title and every paragraph on the website had to be manually modified.The introduction of variables is exactly to solve this pain point.In AnQiCMS template system, variables play a role in dynamically presenting backend data on the front-end page, making the content no longer static text but an active element that can be automatically updated according to data changes.
AnQiCMS template uses syntax similar to Django template engine, where variable usage is intuitive and concise. Any content that needs to be dynamically displayed is usually wrapped in double curly braces{{ }}auto{{ archive.Title }}autoarchiveautoTitleauto
These built-in variables allow you to easily access the data in the current context, such as the page title, description, article content, and even image links. For article detail pages, you can directly access them througharchive.Title/archive.Description/archive.CreatedTimeEnglish version: Get the various information of the document; For the category list page, you can display the details of the category. This direct access mechanism greatly simplifies the presentation of content.category.Title/category.LinkEnglish version: Display the details of the category. This direct access mechanism greatly simplifies the presentation of content.
Flexible definition, use as needed: the power of custom variables
In addition to directly using the variables provided by the system, AnQiCMS also allows us to define our own variables in templates, thus achieving more advanced content organization and logical control. This is mainly realized in two ways:withTags andsetLabel.
When we need to declare some variables temporarily in a local range of a template, like aincludefragment that is introduced,withTags make it very convenient. It provides a clear scope for variables, ensuring that variables are only accessible{% with %}and{% endwith %}Between valid. For example, when you want to pass specific titles and keywords to a common header template, you can use it like this:
{% with title="这是声明给header使用的title" keywords="这是声明给header使用的keywords" %}
{% include "partial/header.html" with title=title keywords=keywords only %}
{% endwith %}
Here,withThe tag definestitleandkeywordsTwo local variables, and they were passed toheader.htmltemplates.onlythe keyword ensuresheader.htmlonly these two explicitly passed variables are received, avoiding unnecessary variable pollution.
whilesetLabels are used to define a variable with a broader scope within the current template file. If you need to reuse a calculated result or a specific value in multiple places within the template,setThe label would be a better choice:
{% set greeting = "欢迎来到我们的网站" %}
<p>{{ greeting }}</p>
This custom variable ability allows you to pre-process or restructure data at the template layer based on complex business logic, without modifying the backend code.
Label联动标签:动态数据的核心
AnQiCMS provides rich template tags for fetching data from the database, such as article lists, category lists, system settings, etc.These tags will assign the queried data to the specified variable during execution, and then we can iterate over these variables to display the content.
For example,archiveList标签用于获取文档列表。当你这样使用它时:
{% archiveList archives with type="page" limit="10" %}
{% for item in archives %}
<div class="article-item">
<h2><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
<p>{{ item.Description|truncatechars:100 }}</p>
<span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
</div>
{% empty %}
<p>暂无文章内容。</p>
{% endfor %}
{% endarchiveList %}
Here are thearchives就是由archiveList标签赋值的变量,它包含了多篇文档数据。通过{% for item in archives %}Loop, each iteration assigns the data of a document toitema variable, then we can access the details of each document throughitem.Link/item.Title/item.Descriptionetc. to access the details of each document.
Similarly,categoryListTags allow you to traverse the categories of a website,navListLabels are used to build complex navigation menus. These labels all follow a similar pattern: store the query results in the variable you specify, and then throughforloop to traverse and display.
Filter: A powerful tool for beautifying and refining variable output
Variables provide the original data, but sometimes we need to format, truncate, or convert the data to better adapt to front-end display.AnQiCMS provides powerful filter functions.|Symbols applied after variables can be chained for multiple data processing.
- Date and time formattingThe time stored on the backend is usually a timestamp and is not suitable for direct display to users.
stampToDateThe filter can convert it into a readable date format, such as{{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}Let the publish time be displayed in the format of "year-month-day hour:minute". - Text truncation: For article summaries or descriptions, we may need to control their display length to avoid long pages.
truncatecharsFilter can truncate text by character count and add an ellipsis at the end, like{{ item.Description|truncatechars:100 }}. If the content contains HTML tags,truncatechars_htmlit can maintain the integrity of the HTML structure while truncating. - Content Security and DisplayWhen displaying the content of rich text editor (such as article text)
archive.Content),to prevent the browser from treating HTML tags as plain text, we need to use|safeFilter, tells the template engine that this content is safe HTML and can be parsed directly. For example:{{ archive.Content|safe }}. - Other practical features: There are many filters that can help you perform string case conversion (
upper,lower,title,capfirst)、remove HTML tags(striptags,removetags)、URL encode(urlencode)and other operations, they together constitute the powerful processing capability of variable output.
Optimize content display and management: comprehensive application of variables
Through the definition, use, and processing techniques of the above variables, we can build highly flexible and easy-to-manage content displays.
- Modular templates: Utilizing
withandincludeLabels can abstract the common parts of a website (such as headers, footers, sidebars) into independent template fragments and pass the required data through variables.This not only reduces code redundancy, but also makes local modifications easy. - Dynamic content layout: Combined with logical judgment (
{% if %}) and loop ({% for %}We can dynamically adjust the page layout and content presentation based on different values of variables. For example, based on the article'sFlagattributes (headlines, recommendations, etc.) to display different styles or locations. - SEO optimization:
tdkTags directly retrieve the title, keywords, and description variables of the page, in cooperation withsystem.SiteNameEnglish variables, which can realize unified and dynamic SEO meta information configuration, enhancing search engine friendliness. The pseudo-static rules for{filename}/{catname}The use of variables such as 'auto' also makes the URL structure more in line with SEO standards. - Support for multiple sites and multiple languages: By specifying in the tag
siteIdThe data from different sites can be called in a single template. At the same time,languagesTags allow dynamic switching of language versions,配合翻译标签coordinated with translation tags{% tr %}to build a truly multilingual website.
You will be able to manage content, design templates more efficiently, and ultimately deliver a website that is both beautiful and powerful after mastering the definition and usage of variables in AnQiCMS templates.
Common Questions and Answers (FAQ)
Q1: How can I define a variable that can be used globally in the template, rather than being limited to a local scope?
A1:In AnQiCMS template, if you want to define a variable and use it at any subsequent location in the current template (including outside of loops and conditional judgments), it is recommended to use{% set variable_name = "your value" %}This way. For example,{% set page_title = "我们的产品" %}can be accessed anywhere in the template after that.