How to correctly reference and display variables in AnQiCMS templates and make conditional judgments to control content display?

Calendar 👁️ 62

In AnQiCMS templates, flexibly referencing variables and using conditional judgments to control content display is the key to building dynamic and feature-rich websites.AnQiCMS uses a template engine syntax similar to Django, which makes template development both intuitive and powerful.This article will delve into how to effectively manage variables and logic in the AnQiCMS template, helping you better control content presentation.


One, AnQiCMS template basics: variable reference and display

In the AnQiCMS template, the flow of data is carried by variables. Understanding how to correctly reference and display these variables is the first step in template development.

1. Overview of Template Engine Syntax

AnQiCMS templates follow specific syntax rules:

  • Variable Reference: Using double curly braces{{ 变量名 }}to output the value of a variable.
  • Logical controlUse single curly braces and percentages{% 标签名 %}Process conditional judgments, loops, function calls, and other logical operations. These logical tags usually appear in pairs, such as{% if 条件 %}...{% endif %}.

2. Variable naming and access

Variables in AnQiCMS are usually written in camelCase, which means the first letter of each word is capitalized. When you need to access a property of an object, use the dot notation.Make a connection.

  • Refer to a simple variable: If you have configured the website name in the background "Global Function Settings" and named itSiteName, you can refer to it in the template like this:

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

    Or use the system tag to explicitly call and assign it to a custom variable name:

    {% system siteNameVar with name="SiteName" %}
    <h1>欢迎来到 {{ siteNameVar }}!</h1>
    
  • Reference object properties When iterating over the document list, each document is an object, you can access it throughitem.Title/item.LinkAccess its properties in this way. For example, display article titles and links in an article list:

    {% archiveList archives with type="list" limit="5" %}
        {% for item in archives %}
            <p><a href="{{ item.Link }}">{{ item.Title }}</a></p>
        {% endfor %}
    {% endarchiveList %}
    
  • Use filters to handle variables: AnQiCMS provides a rich set of filters to format or convert variables. Filters are separated by a vertical line|Connected after the variable name, can be concatenated for use. For example, if your article contentitem.ContentTags containing HTML, to safely display this content without being directly parsed by the browser as malicious script, you can usesafeFilter:

    <div>{{ item.Content|safe }}</div>
    

    For example, formatting a timestampitem.CreatedTimeFor a readable date:

    <p>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</p>
    

    For string truncation, you can usetruncatechars:

    <p>简介:{{ item.Description|truncatechars:50 }}</p>
    

3. Custom variables

Sometimes you need to temporarily create or assign a variable in the template, AnQiCMS provideswithandsetTo achieve this with a tag.

  • {% with %}TagUsed to define one or more variables within a scope, usually in conjunction withincludetags to pass variables to included template fragments.
    
    {% with greeting="你好" name="世界" %}
        <p>{{ greeting }}, {{ name }}!</p>
    {% endwith %}
    
  • {% set %}TagUsed to declare a variable within the current template scope, its scope extends until the template ends or is overridden by a newsettag.
    
    {% set articleCount = 0 %}
    {% archiveList archives with type="list" limit="10" %}
        {% for item in archives %}
            {% set articleCount = forloop.Counter %}
            <p>{{ articleCount }}. {{ item.Title }}</p>
        {% endfor %}
    {% endarchiveList %}
    <p>共有 {{ articleCount }} 篇文章。</p>
    

Flexible control of content display: conditional judgment (If statement)

Conditional judgment is the core of template logic, allowing you to display or hide specific content blocks based on different conditions. It is AnQiCMS'sifstatement syntax is intuitive and feature-rich.

1.{% if %}/{% elif %}/{% else %}structure

The most common conditional judgment structures includeif(if),elif(else if),else(otherwise) andendif(end if).

{% if 用户已登录 %}
    <p>欢迎回来,{{ 用户名 }}!</p>
{% elif 用户正在注册 %}
    <p>欢迎注册新账号!</p>
{% else %}
    <p>请登录或注册。</p>
{% endif %}

2. Common Conditional Judgment

  • Equal and Unequal: Use.==(Equal) and!=(Not Equal).
    
    {% if category.Id == 1 %}
        <p>这是新闻分类的特别内容。</p>
    {% endif %}
    
  • Size Comparison: Use.>,<,>=,<=.
    
    {% if archive.Views > 1000 %}
        <span class="hot-badge">热门</span>
    {% endif %}
    
  • Logical Operation: Use.and(AND),or(OR),not(Not).
    
    {% if user.IsVIP and user.ExpireTime > currentTime %}
        <p>您是尊贵的 VIP 会员。</p>
    {% elif not user.IsVIP %}
        <p>成为 VIP 享受更多特权。</p>
    {% endif %}
    
  • Check if a variable exists or is not empty: Use the variable name directly as a condition, when the variable isnil, empty string, zero value, etc. it will be judged asfalse.
    
    {% if archive.Thumb %}
        <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
    {% else %}
        <img src="/static/images/default_thumb.jpg" alt="默认缩略图">
    {% endif %}
    

3. Application in Real Scenes

Conditional judgments are widely used in various scenarios, such as:

  • Navigation menus displayed differently based on user roles.
  • Images or placeholders are displayed based on whether the article has a thumbnail.
  • On the list page, based on the article'sFlagAdd special styles or tags to properties (such as "Recommendation", "Headline")
  • In multi-site management, according tositeIdLoad different content or layouts.

Traversing data collections: Loop (For statement)

Loops are a powerful tool for handling data lists, whether it's an article list, category list, or navigation menu,forSentences can help you render efficiently.

1.{% for %}/{% endfor %}structure

forLoops are used to iterate over each element in an array, slice (slice), or other iterable objects.

{% categoryList categories with moduleId="1" parentId="0" %}
    <ul>
        {% for category in categories %}
            <li><a href="{{ category.Link }}">{{ category.Title }}</a></li>
        {% endfor %}
    </ul>
{% endcategoryList %}

2.forloopObjects and auxiliary functions

InforInside the loop, you can access a specialforloopAn object that provides information about the current loop state.

  • forloop.CounterThe current iteration number (starting from 1).
  • forloop.Revcounter: The remaining number of iterations in the loop (counting backwards).
    
    {% archiveList archives with type="list" limit="3" %}
        {% for item in archives %}
            <p>{{ forloop.Counter }}. {{ item.Title }} (还剩 {{ forloop.Revcounter }} 篇)</p>
        {% endfor %}
    {% endarchiveList %}
    

3

Related articles

What website modes does AnQiCMS support to meet the display needs of adaptive, code adaptation, or independent sites for PC+mobile?

In today's multi-screen interconnected digital age, whether a website can present excellent display effects on various devices is directly related to user experience, brand image, and even business conversion.AnQiCMS as an efficient and flexible content management system fully understands this core need, providing users with a variety of website display modes to ensure that your content reaches the target audience perfectly on any terminal.AnQiCMS has carefully designed three mainstream website models to meet the display needs of adaptive, code adaptation, or independent sites for PC and mobile endpoints

2025-11-08

How can AnQiCMS significantly improve website loading speed and content display efficiency through static caching and SEO optimization?

In today's fast-paced online world, slow website loading speed not only drives away visitors but may also make your content 'disappear' in search engines.User experience and search engine optimization (SEO) are the two cornerstones of website success, and both are closely related to the website's response speed and content display efficiency.AnQiCMS is a content management system developed based on the Go language, fully aware of these pain points, and therefore, from the very beginning of its design, it has taken static caching and SEO optimization as core advantages, aiming to significantly improve the performance of the website.

2025-11-08

How do website operators understand the display data of website traffic and spider crawling through the AnQiCMS backend?

## Mastering AnQiCMS Backstage: Understanding Website Traffic and Crawler Extraction Dynamics In today's digital marketing environment, understanding the performance of website traffic and the crawling situation of search engine spiders is crucial for website operators.This not only helps us evaluate the effectiveness of content strategy, but also enables us to detect and resolve potential SEO problems in a timely manner.AnQiCMS is a powerful content management system that provides users with intuitive and detailed backend data, allowing us to easily grasp these key information.

2025-11-08

How AnQiCMS can protect the display copyright of original content through anti-crawling and watermark functions?

Today, with the explosive growth of digital content, the value of original content becomes increasingly prominent.However, the problem of content collection and theft that follows also makes every content creator and operator headaches.Imagine, the high-quality articles and meticulously designed images you have put your heart and soul into, are suddenly taken by others without permission. This not only infringes on copyright but may also have a negative impact on your website's SEO and brand image.Faced with such challenges, AnQiCMS (AnQiCMS), as an enterprise-level content management system developed based on the Go programming language, has raised content copyright protection to the core function level

2025-11-08

How to set up independent templates for specific articles, categories, or single pages to achieve customized content display?

In website operation, we always encounter some unique content, which may represent a special promotional event, an important corporate report, or a page that needs to be presented specially.This content often does not meet the unified default style of the website, and needs its own 'face' to attract users and highlight the key points.AnQiCMS (AnQiCMS) fully understands this need, therefore it provides a very flexible template customization feature, allowing us to easily set up independent templates for specific articles, categories, or single pages, achieving customized content display.Why do we need an independent template

2025-11-08

How to call and categorize the recommended attributes (such as headlines, sliders) of AnQiCMS articles on the frontend?

How to make important and excellent content stand out and attract users' attention at the first time is the key to improving user experience and content marketing effectiveness in website operation.AnQiCMS provides a very practical recommendation attribute mechanism, which helps us easily classify and highlight content, such as setting hot articles as 'Headlines' or displaying selected products in the 'Slider' area.

2025-11-08

How to use the AnQiCMS timing publishing function to control the display time of content and achieve automated operation?

In the daily work of content operation, maintaining the continuous update and scheduled release of website content is a key factor in attracting users and enhancing brand influence.However, manually publishing content is not only time-consuming, but also limited by the time and energy of operation personnel, especially when it is necessary to target global users, cross-time zones, or carry out a series of content promotions, the challenges are even greater.AnQiCMS (AnQi CMS) precisely understands these pain points, cleverly integrates the powerful timing publishing function, helps you achieve automated content operation, and keep your website always vibrant.

2025-11-08

How to add keywords and Tag tags in article content and display them associated in detail pages or list pages?

In Anqi CMS, effectively utilizing keywords (Keywords) and tags (Tags) is the key to optimizing content structure, improving search engine visibility (SEO), and enhancing user experience.They not only help websites to better organize content, but also guide users to discover more related information.Next, we will delve into how to reasonably add these elements to the article content and ensure they can be displayed correctly on the website's detail page or list page.### One, add keywords to the article content Keywords are words that describe the core theme of the article

2025-11-08