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

Calendar 👁️ 67

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.

Related articles

How to use the pseudo-static function of Anqi CMS to optimize the display structure of URLs and improve SEO effects?

In website operation, the structure of URL (Uniform Resource Locator) has a significant impact on the SEO performance of the website.A clear, concise, and meaningful URL not only improves user experience but also helps search engines better understand and crawl web content.AnQiCMS (AnQiCMS) is well-versed in this field, providing powerful static URL features to help us easily optimize the display structure of URLs, thereby significantly enhancing SEO effects.

2025-11-08

How to configure the display of page TDK (title, keywords, description) for search engine optimization (SEO) in Anqi CMS?

It is crucial for website operation to let search engines better understand and display our content.This configuration of page TDK (Title, Description, Keywords) plays a core role.AnQi CMS provides us with flexible and powerful TDK management functions, allowing us to accurately optimize search engine optimization according to the characteristics of different pages.Next, we will learn step by step how to configure these key TDK information in Anqi CMS.### One, Global Setting of Website Homepage TDK The website homepage is the facade

2025-11-08

How can AnQi CMS manage and display multilingual content to support international promotion?

Under the wave of globalization, does your website desire to reach a wider audience?Providing content in the native language for users of different languages can not only greatly enhance the user experience, but is also a key step in expanding into the international market.AnQiCMS (AnQiCMS) is well aware of this need, and from the very beginning of its design, it has made multilingual support one of its core features, making content internationalization simple and efficient. ### Content Organization and Presentation: Multi-site Collaboration and Language Package Support Anqi CMS provides a clear and efficient logic for managing multilingual content. First

2025-11-08

How to create and display breadcrumb navigation to enhance user experience and page structure visibility?

In website operation, clear navigation is the key to improving user experience.When a visitor delves into the internal pages of a website, a well-designed and easy-to-understand breadcrumb navigation can effectively help them understand their current location and provide a quick way to return to the upper-level page.This not only makes the website structure clear, but also helps search engines better understand the website hierarchy, indirectly optimizing SEO.AnQiCMS (AnQiCMS) fully understands the importance of navigation and has built-in very practical breadcrumb navigation features

2025-11-08

What tags does Anqi CMS provide to display content publishing or update time information?

In website content operation, the time of content release and update is a key factor in conveying information timeliness and establishing user trust.For search engine optimization (SEO), clear time information also helps improve the freshness score of the content.Anqi CMS is well-versed in this, providing users with flexible and diverse tags and methods to accurately and beautifully display these time information on the website front-end.Next, we will explore how Anqi CMS helps us manage and display the content publication and update time.###

2025-11-08

How to display the link to the previous and next article on the Anqi CMS content page?

In AnQi CMS, it is a common need to add navigation links for "Previous Article" and "Next Article" to enhance the user experience of the website and the efficiency of internal links.These links not only help visitors browse related content more smoothly, but also have a positive impact on the website's SEO performance.AnQi CMS provides a set of intuitive template tags that allow you to easily display these navigation features on the content detail page.### Core Function: Use `prevArchive` and `nextArchive` tags Anqi CMS passes through

2025-11-08

How to display a list of recommended content related to the current article?

In content operation, guiding users to discover more interesting content is one of the key strategies to enhance user experience and extend the time spent on the website.AnQiCMS (AnQiCMS) provides very flexible and powerful features, helping us easily achieve the goal of displaying a list of recommended content related to the current article.Why is it necessary to have relevant recommended content?

2025-11-08

How does Anqi CMS display and manage website friend links?

In website operation, friendship links play an important role. They not only help to improve the website's search engine ranking (SEO), but also bring valuable traffic, and are also a manifestation of cooperation and mutual trust between websites.Anqi CMS is well-versed in this, providing website operators with a直观 and efficient buddy link management and display solution, allowing you to easily master this feature.Next, we will delve into how to manage friend links in the background, to how to flexibly display them on the website frontend, and provide you with a detailed explanation of the friend links feature of Anqi CMS.

2025-11-08