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

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