In AnQi CMS, flexibly using template variables is the key to optimizing website content display and management efficiency.It not only makes your website content more dynamic, but also greatly improves 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 better present content through these techniques.

Variables: The foundation for bringing content to life

Imagine if every title, every description on a website had to be manually modified, that would be so cumbersome.The introduction of variables is to solve this pain point. In the AnQiCMS template system, variables play a role in dynamically displaying backend data on the front-end page, making the content no longer static text, but an active element that can automatically update according to data changes.

The AnQiCMS template uses a syntax similar to the Django template engine, where the use of variables is intuitive and concise. Any content that needs to be dynamically displayed is usually enclosed in double curly braces{{ }}Among them. For example, if you want to display the title of a document, you will see something like{{ archive.Title }}such writing. Here,archiveusually represents the document object of the current page, whileTitleis an attribute of the document object.

These built-in variables allow you to easily access the current context data, such as the title of the page, description, article content, and even image links. For article detail pages, you can directly accessarchive.Title/archive.Description/archive.CreatedTimeWait to obtain all the information of the document; for the category list page, you can access it throughcategory.Title/category.LinkWait to display the details of the category. This direct access mechanism greatly simplifies the presentation of the content.

Define flexibly, 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 the template, thereby achieving more advanced content organization and logical control. This is mainly achieved in two ways: withTags andset.

When we need to declare some temporary variables in a local scope of a template, like aincludefragment that is introduced, withLabels make it very convenient. They provide a clear scope for variables, ensuring that variables are only accessible{% with %}and{% endwith %}valid between. For example, when you want to pass specific title 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 defines.titleandkeywordsTwo local variables, and passed them toheader.htmlTemplate.onlyThe keyword ensuresheader.htmlOnly received these two explicitly passed variables, avoiding unnecessary variable pollution.

AndsetTags are used to define a variable with a broader scope in the current template file. If you need to reuse a calculated result or a specific value at multiple locations in the template,setthe tag would be a better choice:

{% set greeting = "欢迎来到我们的网站" %}
<p>{{ greeting }}</p>

This custom variable capability allows you to preprocess or reorganize data at the template level based on complex business logic without modifying the backend code.

Label联动 with variables: the core of dynamic data

AnQiCMS provides rich template tags for fetching data from the database, such as article lists, category lists, system settings, and so on.These tags, when executed, will assign the queried data to designated variables, and then we can iterate over these variables to display the content.

For example,archiveListLabel used to get the document list. When you use it like this:

{% 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 %}

HerearchivesIt is byarchiveListThe variable assigned by the label, it contains multiple document data. Through{% for item in archives %}The loop assigns the data of a document to a variable each iterationitemThen we can access the details of each document byitem.Link/item.Title/item.Descriptionetc.

Similarly,categoryListTags allow you to traverse the categories of the website,navListTags are used to build complex navigation menus. These tags follow a similar pattern: store the query results in the variable you specify, then traverseforand display in a loop.

Filter: A 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 a powerful filter function for this.The filter passes|The symbol can be applied after the variable, allowing for chained calls to achieve multiple data processing.

  • Date and time formatting: The time stored on the backend is usually a timestamp, which is not suitable for direct display to users.stampToDateThe filter can convert it to a readable date format, such as{{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}Let the release time be displayed in the format of "Year-Month-Day Hour:Minute".
  • Text truncation: For the article summary or description, we may need to control the display length to avoid long pages.truncatecharsThe filter can truncate text by character count and add an ellipsis at the end, such as{{ 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 Display: When displaying the content entered in a rich text editor (such as an article bodyarchive.Content), to prevent HTML tags from being displayed as plain text by the browser, we need to use|safeA filter that tells the template engine that this content is safe HTML and can be parsed directly. For example:{{ archive.Content|safe }}.
  • Other practical functionsThere are many filters that can help you perform string case conversion(upper,lower,title,capfirst), remove HTML tags(striptags,removetags), URL encoding(urlencodeOperations such as these, together, constitute the powerful processing capability of variable output.

Optimize content display and management: comprehensive application of variables.

By defining, using, and processing the above variables, we can build a highly flexible and easy-to-manage content display.

  • Modular templateUtilizewithandincludeTags, 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 repetition, but also makes local changes 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 variable values. For example, based on the article'sFlagProperties (Headlines, Recommendations, etc.) display different styles or locations.
  • SEO optimization:tdkTags directly obtain the title, keywords, and description variables of the page, in conjunction withsystem.SiteNameUniform global variables can be used to implement unified and dynamic SEO metadata configuration, improving search engine friendliness. In the static rule of{filename}/{catname}Using variables also makes the URL structure more SEO-friendly.
  • Support for multiple sites and languages: Specify in the tag.siteIdYou can call data from different sites in a template. At the same time,languagesTags allow dynamic switching of language versions,配合 translation tags{% tr %}You can build a true multilingual website.

Mastering the definition and usage of variables in AnQiCMS templates, you will be able to manage content and design templates more efficiently, and ultimately deliver a website that is both beautiful and powerful.


Frequently Asked Questions (FAQ)

Q1: How can I define a variable that can be used globally in a template instead of being limited to a local scope?

A1:In the AnQiCMS template, if you want to define a variable and be able to 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 used anywhere in the template afterwards