How to define and use variables for content display in AnQiCMS templates?

Calendar 👁️ 72

AnQiCMS (AnQiCMS) boasts its efficient architecture based on the Go language and flexible template mechanism, making content presentation both powerful and intuitive.In website content operation, we often need to display dynamic information, such as article titles, product prices, contact information, etc., which cannot be separated from defining and using variables in templates.Understanding how to flexibly use variables in AnQiCMS templates is the key to building and maintaining an efficient, personalized website.

The template engine of AnQi CMS has borrowed the syntax of Django, which makes variable definition and reference very easy to understand.Essentially, any data that needs to be dynamically displayed, whether from system configuration, database content, or temporary calculated values, can be manipulated in the template using variables.Variables are usually enclosed in double curly braces{{ 变量名 }}The form appears while performing logical judgments or loop operations, and single curly braces and percentage signs are used{% 标签名 %}.

Understanding the source of variables in the template

In AnQiCMS templates, there are mainly three sources of variables:

  1. Variables provided automatically by the systemAt the time of visiting a specific page, the system automatically passes some core data to the template, which can be used directly in the template. For example, on the article detail page,archiveThe variable will contain all the information of the current article (such asarchive.Title/archive.Content);On the category list page,categorythe variable represents the data of the current category. In addition, likepagesSuch variables will carry pagination information, no need for us to manually obtain it.

  2. Variables obtained and defined through built-in tags.This is the most commonly used way to retrieve and display specific data. AnQiCMS provides a wealth of built-in tags such assystem/contact/archiveList/categoryListThese tags can not only query data on demand, but also assign the query results to a custom variable name for further use in the template.

    For example, if you want to display the website name in the footer, you can directly call the system settings tag:

    <div>网站名称:{% system with name="SiteName" %}</div>
    

    If you need to use this website name multiple times or want to process it further, it is best to assign it to a variable:

    {% system siteNameVar with name="SiteName" %}
    <div>网站名称:{{ siteNameVar }}</div>
    

    Thus,siteNameVarThe website name is included, and we can reference it multiple times in the subsequent template code. For situations that require list data, such as article lists, we will define a variable like thisarchivesStore the query result:

    {% archiveList archives with type="list" categoryId="1" limit="10" %}
        {% for item in archives %}
            <p><a href="{{ item.Link }}">{{ item.Title }}</a></p>
        {% endfor %}
    {% endarchiveList %}
    

    Here, archivesIt has become an array containing multiple articles, we traverseforBy looping through it, and byitem.Linkanditem.TitleAccessing the links and titles of each article.

  3. Custom variable inside the templateSometimes, we need to define some temporary variables in the template to store calculation results, phrases, or pass data to other modules. AnQiCMS provides two commonly used methods:

    • {% with ... %}{% endwith %}This kind of variable definition is only valid inwiththe internal tag, usually used to passincludeparameters to a tag, or to define temporary variables within a local code block.

      {% with greeting="Hello AnQiCMS User!" %}
          <p>{{ greeting }}</p>
      {% endwith %}
      {# 在这里,greeting 变量将不再有效 #}
      
    • {% set ... %}:setThe variable defined by the tag has a wider scope in the current template file, starting from the definition location until the end of the template.

      {% set pageTitle = "关于我们" %}
      <title>{{ pageTitle }}</title>
      {# 稍后在页面其他地方依然可以使用 pageTitle #}
      <p>欢迎来到{{ pageTitle }}页面。</p>
      

      These two methods have their respective focuses,withEmphasizing scope isolation, andsetIt is more suitable to share data throughout the template.

Access variables' properties and call methods

Once a variable is defined, we can use a point to access it..) symbols are used to access their internal properties or fields. For example, ifarchiveis an article object variable, then{{ archive.Title }}will display the article title,{{ archive.CreatedTime }}and then the creation time will be displayed.

We usually combine{% for ... in ... %}{% endfor %}loop tags to iterate over each element and access the properties of each element inside the loop:

{% archiveList latestNews with type="list" limit="5" %}
    <ul>
        {% for newsItem in latestNews %}
            <li><a href="{{ newsItem.Link }}">{{ newsItem.Title }}</a></li>
        {% endfor %}
    </ul>
{% endarchiveList %}

In this example,latestNewsis a variable for the article list, looped innewsItemrepresents each article object in the list.

AnQiCMS templates also support directly calling the public methods defined in the Go language structure. For example, if the article objectitemhas a namedGetThumb()The method to get thumbnails, we can directly call it like this in the template:

<img src="{{ item.GetThumb() }}" alt="{{ item.Title }}">

Use filters to handle variables

AnQiCMS template engine is built-in with a rich set of filters (Filters), which allow us to process variable values in various ways, such as formatting, truncation, escaping, etc. Filters are passed through the pipe character|Connected at the end of the variable.

Some commonly used filters include:

  • |safeWhen the variable content contains HTML code (such as article detailsContentfield), use|safeCan prevent the template engine from escaping it, so that the HTML code renders normally.
    
    <div>{% archiveDetail articleContent with name="Content" %}{{ articleContent|safe }}</div>
    
  • |stampToDate:"格式": Used to format timestamps into readable date or time strings.
    
    <p>发布时间:{{ stampToDate(archive.CreatedTime, "2006年01月02日 15:04") }}</p>
    
  • |truncatechars:数字: Truncate the string to a specified length and add an ellipsis at the end.
    
    <p>{{ archive.Description|truncatechars:100 }}</p>
    
  • |default:"默认值": If the variable has no value or is empty, display a default value.
    
    <p>作者:{{ archive.Author|default:"佚名" }}</p>
    
    The filter greatly enhances the flexibility of template data processing, allowing us to present more diverse content on the front end without modifying the background logic.

Summary

To define and use variables in AnQiCMS is a core step from static pages to dynamic content display.Whether it is to quickly obtain data through the system's built-in variables, or to customize queries using built-in tags, or to directly define temporary variables in the template, it provides us with great flexibility.We can build a website with rich features and excellent user experience by combining dot notation to access properties, iterating over data, and applying filters for formatting.Mastering the techniques of these variables will make your content operation work more skillful.


Frequently Asked Questions (FAQ)

1. How to view what data and structure a variable contains?

If you are unsure about the internal structure or data contained in a variable during template development, you can use{{ 变量名 | dump }}Filter. It will directly print the detailed structure of the variable on the page

Related articles

How to reference and display external static resources (such as CSS, JS) in the template?

Referencing and displaying external static resources in AnQiCMS templates, such as CSS style sheets and JavaScript scripts, is a key step in building a functional and visually appealing website.Understand the working principle and recommended practices, which can make our website development work more efficient and flexible.

2025-11-07

How to reflect the high concurrency characteristics of the Go language in the front-end page loading speed?

In today's fast-paced online world, website loading speed has become a core factor in user experience and search engine rankings.Nobody likes to wait for a slow page, and search engines tend to rank websites that respond quickly higher.How can you make your website lightning fast?For users of AnQiCMS, the answer is hidden in its powerful Go language underlying architecture, especially the high concurrency features that Go language boasts.

2025-11-07

How to dynamically display the current year or current time in a template?

In website operation, we often need to dynamically display the current year or time, such as displaying the latest copyright year at the bottom of the website, or marking the generation time of the page accurately in articles.AnqiCMS provides flexible and powerful template functions, making these operations very simple.Next, we will discuss how to implement this requirement in the AnqiCMS template.

2025-11-07

How to safely display rich text content containing HTML tags on the front-end page?

In website operation, we often need to display rich content that includes images, links, bold text, and so on, which is known as rich text content.But it is a practical and careful task to safely display these rich text with HTML tags on the front-end page.AnQi CMS as an efficient content management system, fully considers this point, and provides us with a clear solution.

2025-11-07

How to categorize image resources and display them on the front end according to categories?

Images are an indispensable part of a website's content, as they can not only beautify the page but also effectively convey information and enhance the user experience.However, with the increase in the number of images on a website, how to efficiently manage these image resources and flexibly display them on the front page as needed has become a challenge for many website operators.AnQiCMS (AnQiCMS) is well-versed in this field, providing a user-friendly and powerful image resource management system that helps us easily manage these visual elements.

2025-11-07

How to configure 301 redirect rules to avoid SEO impact after content adjustment?

Website content operation is a continuous job, with the development of the business, content updates, adjustments, and even optimization of the website structure can lead to changes in page URLs.However, if these URL changes are not handled properly, they often have a significant negative impact on the website's search engine optimization (SEO), such as a drop in rankings, loss of traffic, and so on.This is when the 301 redirect becomes a key tool for us to avoid these negative impacts and maintain the SEO health of the website.### Understanding the value of 301 redirect In simple terms, 301 redirect (Moved

2025-11-07

How to organize reusable display modules in a template through `include`, `extends`, and other tags?

Aq enterprise CMS template: Use `include` and `extends` to create efficient and reusable display modules When using Aq enterprise CMS to build a website, you will quickly find that it is very flexible in organizing content display.Especially when dealing with templates, the built-in Django template engine syntax allows us to build pages efficiently like building with blocks.Today, let's talk about how to cleverly use the powerful tags `include` and `extends` to organize and manage reusable display modules on your website, making your templates cleaner and easier to maintain

2025-11-07

How to display a friendly prompt page to users during website maintenance or upgrade?

During the operation of the website, whether it is system upgrades, data migration, or routine maintenance, it is inevitable that there will be situations where the website needs to be temporarily closed or some functions cannot be accessed.How to convey clear and friendly information to users visiting the website at this time, to avoid confusion or direct loss of users, is the key to improving user experience and maintaining brand image.lucky enough, AnQiCMS provides a simple and efficient mechanism to help us easily deal with such situations. ### Why is it necessary to have a friendly maintenance page for website upgrades?

2025-11-07