How to judge conditions in templates and dynamically display different content blocks based on logic?

In AnQiCMS, flexibly controlling the display of web page content is the key to website operators building personalized, high-efficiency websites.The AnQiCMS template engine provides rich logical judgment and dynamic content display capabilities, allowing us to intelligently present content based on different conditions, greatly enhancing user experience and website adaptability.

AnQiCMS's template syntax is cleverly designed, drawing on the advantages of the Django template engine while also taking into account the characteristics of the Go language. This means that in template files, we will usually see the use of two types of curly braces: double curly braces{{ 变量 }}Used to output variable content, while the single curly braces percent sign{% 标签 %}It is used to implement various logical controls, such as conditional judgments, loops, etc. Understanding and effectively using these tags and variables is the first step to achieving template dynamization.

Basic conditional judgment in AnQiCMS templates

The core of realizing dynamic content display lies in conditional judgment. AnQiCMS usesifThe tag family provides us with powerful logical judgment tools. Its basic structure is similar to that of many programming languages:

{% if 条件 %}
    <!-- 条件为真时显示的内容 -->
{% elif 其他条件 %}
    <!-- 其他条件为真时显示的内容 -->
{% else %}
    <!-- 以上条件都不为真时显示的内容 -->
{% endif %}

In here, “condition” can be any expression that returns a boolean value (true or false). We can use common comparison operators, such as equal to==, not equal to!=, greater than>, less than<and greater than or equal to>=and less than or equal to<=. Logical operator at the same timeand/or/notas well asinIt also provides convenience for us to construct complex judgments.For example, we can determine whether a variable exists, whether it is a specific value, or whether a string contains a specific keyword.

Use case one: Display based on whether the variable exists or has a value

The website content is not always complete, sometimes some fields may be empty.In order to avoid blank pages or error prompts on the page, we can first determine if the variable has a value before deciding whether to display the relevant content.

A common example is the display of images. If an article has not set a thumbnail, we do not want a broken image icon to appear on the page. At this time, we can judge in this way:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}" />
{% else %}
    <!-- 如果没有缩略图,可以显示一个占位图或什么也不显示 -->
    <img src="/static/images/placeholder.png" alt="无图" />
{% endif %}

Herearchive.ThumbIt returns true when there is a value, false when there is no value. Similarly, for article descriptionarchive.DescriptionCustom fields and the like can be used to control display. If a variable may be empty, but we still want it to display something, we can usedefaultA filter is used to set default values, such as{{ archive.Description|default:"暂无描述" }}This can effectively avoid visual problems caused by empty content.

Use case two: judgment based on specific numeric or boolean values

In navigation, list display, and other scenarios, we often need to dynamically adjust content based on ID, status, or boolean values.

For example, in a navigation menu, we may need to highlight the navigation item corresponding to the current page, at this timeIsCurrentthis boolean value comes into play:

{% navList navs %}
    <ul>
    {%- for item in navs %}
        <li class="{% if item.IsCurrent %}active{% endif %}">
            <a href="{{ item.Link }}">{{item.Title}}</a>
        </li>
    {% endfor %}
    </ul>
{% endnavList %}

By{% if item.IsCurrent %}We can dynamically add the current navigation itemactiveClass name, to implement highlighting.

For example, when we need to determine whether a category has subcategories in the category list,item.HasChildrenthis boolean value can help us decide whether to display the second-level menu:

{% categoryList productCategories with moduleId="2" parentId="0" %}
    {% for item in productCategories %}
    <a href="{{item.Link}}">{{item.Title}}</a>
    {% if item.HasChildren %}
        <ul class="sub-category-menu">
            <!-- 显示子分类的逻辑 -->
        </ul>
    {% endif %}
    {% endfor %}
{% endcategoryList %}

CombineandandorLogical operators can be used to construct more complex judgments, such as determining whether a user is logged inandHas specific permissionsorIs an administrator, thereby displaying different function buttons.

Useful scenario three: handling dynamic display in lists and loops

Lists are one of the most common content organization forms on websites. AnQiCMS'sforLoop labels can not only traverse data but also combineemptyLabels elegantly handle the case of an empty list:

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
        <!-- 显示文章内容的HTML -->
    {% empty %}
        <div>暂时没有文章内容,敬请期待!</div>
    {% endfor %}
{% endarchiveList %}

So whenarchivesWhen the list has no data, we can display a friendly prompt to the user instead of a blank space.

In loops, we often need to change the style or behavior of the content based on the order of the loop. AnQiCMS providesforloop.Counter(current loop count, starting from 1) andforloop.Revcounter(remaining loop count, counting from 1 to 0) and other variables.

For example, to implement different background colors for odd and even rows:

{% for item in archives %}
    <li class="{% if forloop.Counter is divisibleby:2 %}even{% else %}odd{% endif %}">
        {{ item.Title }}
    </li>
{% endfor %}

HeredivisiblebyFilter judgmentforloop.CounterCan be divided by 2, thereby adding different class names to odd and even rows.

Furthermore,cycleTags allow us to cycle through a series of preset values, often used to implement color, image path cycling, or insert different separators between list items.

Useful scenario four: judgment and operation of string content

In addition to simple existence judgment, sometimes we also need to perform more detailed checks on the specific content of the string.

For example, we want to judge the title of the articleitem.Titlewhether it contains a specific keyword:

{% if item.Title|contain:"AnQiCMS" %}
    <span class="highlight">推荐</span>
{% endif %}

HerecontainThe filter can determine whether the string contains specified content.

When the content obtained from the backend contains HTML code that needs to be processed, such as the content output by a rich text editor, we need to use|safeA filter to ensure that HTML code can be correctly parsed by the browser, rather than being escaped into plain text:

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

And if the content is too long, you can usetruncatecharsortruncatewordsThe filter performs truncation and automatically adds an ellipsis.

Advanced techniques and **practice**

  • Filter chaining call:Multiple filters can be chained together to perform multiple operations on variables, such as{{ article.Title|truncatechars:20|upper }}first truncating and then converting to uppercase.
  • Remove blank lines:While using{% if %}or{% for %}When logical tags are used, unnecessary blank lines may sometimes occur. These blank lines can be effectively removed by using hyphens at the beginning and end of the tags.{%-and-%}These blank spaces can be effectively removed.
  • Variable definition: {% set ... %}Variables can be defined in the current template, while{% with ... %}is more commonly used toincludePass local variables to the template fragments introduced, maintaining the modularity and clarity of the code.
  • Template reuse:Make good use ofincludeTags will apply to common page header, footer, sidebar, etc.