How to use the `if` tag in AnQiCMS templates for conditional judgment to control content display?

Calendar 👁️ 73

When managing content in AnQi CMS, we often need to display different information based on different situations.For example, one blog post may have a thumbnail while another does not;Or a module may only be displayed under certain conditions. In this case, flexibly use the conditional judgment in the template, that is,ifTags, can help us achieve these dynamic content display needs.

The template engine of Anqi CMS supports syntax similar to Django, whereifThe tag is the core tool for conditional judgment. It can decide which part of the content should be rendered and which part should be hidden based on the value of the variable or the result of the expression.

Why is it neededifTag for conditional judgment?

Imagine that we want a certain area of the website to intelligently adapt to different content states. For example:

  • Display an image or a default placeholder:If the article has a cover image, it will display the cover; if not, it will display a preset default image.
  • Active state of the navigation menu:The currently visited page is highlighted in the navigation menu.
  • Distinguish content types:For the 'article' model, display author information; for the 'product' model, display price information.
  • Handle empty data:When a list is empty, it should display 'No data' instead of a blank space.

All these scenarios cannot do without conditional judgments.ifTags allow us to create more adaptable and user-friendly templates.

ifBasic usage of tags

ifThe most basic structure of tags is{% if 条件 %}and{% endif %}. The code placed between these two tags, only when条件It will display when true.

A simple example is to check if a variable exists or is true.In AnQiCMS, many variables are considered false when they have no value.For example, we can determine whether an article has a thumbnail:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% endif %}

The meaning of this code is: ifarchive.Thumb(The thumbnail image path) exists and has a value, then this image will be displayed. Otherwise, the code for the image section will be ignored.

IntroductionelseHandle alternative cases

When we want to display other content when the condition is not met instead of just leaving it blank, we can useelsea tag. It acts asifThe supplement provides a mechanism to execute here if all previous conditions are not met.

Continue with the thumbnail example, if the article does not have a thumbnail, we want to display a default placeholder:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% else %}
    <img src="/static/images/default-thumb.png" alt="默认占位图">
{% endif %}

This way, there will always be an image on the page to maintain the layout integrity, regardless of whether the article has a thumbnail.

More conditions:elifthe flexible application

In some cases, we may need to judge multiple mutually exclusive conditions. At this point,elifthe (else if abbreviation) tag comes into play. It allows us toifWithin the block, multiple conditions are checked in sequence. Once a condition is met, the corresponding code will be executed, and the restelifandelsewill be skipped.

For example, we want to base the article's "recommended properties" on the following conditions (Flag) to display different tags:

{% if archive.Flag == 'h' %}
    <span class="badge hot">头条</span>
{% elif archive.Flag == 'c' %}
    <span class="badge recommend">推荐</span>
{% else %}
    <span class="badge normal">普通</span>
{% endif %}

This code will be based on the attributes of theFlagProperty value, shows the mark of "Headline", "Recommend" or "Normal".

Combine complex conditions: logical operators

ifLabels not only support simple value judgment, but can also be combined with logical operators to construct more complex conditional expressions. The AnQiCMS template engine supports common logical operators such asand(Logical AND),or(Logical OR),not(Logical NOT), as well as comparison operators==(equal to),!=(Not equal),<(Less than),>(greater than),<=(less than or equal to),>=(Greater than or equal to). Moreover,inOperators can check if an element is contained within a collection (such as a string, array).

  • Check if multiple conditions are met:andWe will only display 'Hot Headline' when the article is 'Top Story' and the views exceed 1000:

    {% if archive.Flag == 'h' and archive.Views > 1000 %}
        <span class="badge super-hot">热门头条</span>
    {% endif %}
    
  • Check if any condition is met:orIf the article is 'recommended' or has the 'image' attribute, a special style should be displayed:

    {% if archive.Flag == 'c' or archive.Flag == 'p' %}
        <div class="special-highlight">...</div>
    {% endif %}
    
  • Reverse judgment:notIf the category does not have subcategories, display the document list under the category:

    {% if not category.HasChildren %}
        {% archiveList archives with type="list" categoryId=category.Id limit="8" %}
            {# ... 显示文档列表 ... #}
        {% endarchiveList %}
    {% endif %}
    
  • Check for inclusion:inIf certain specific keywords are included in theKeywordsfield, display specific content.

    {% if "AnQiCMS" in archive.Keywords %}
        <span>安企CMS专属内容</span>
    {% endif %}
    

Practice with AnQiCMS template tags

ifThe power of tags lies in their combination with various data tags provided by AnQiCMS (such asarchiveList/categoryDetailetc.)

  • Active state of the navigation menu:Commonly used in navigation lists, to add menu items corresponding to the current pageactivethe class name.

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

    Hereitem.IsCurrentIs a boolean value, when the current navigation item matches the current pagetrue.

  • Handle list empty content:While usingforWhen traversing the list, if the list is empty, you can useemptyLabels to display prompt information, which is actuallyifA shorthand form of judgment, very practical.

    {% archiveList archives with type="page" limit="10" %}
        {% for item in archives %}
            {# ... 显示文章内容 ... #}
        {% empty %}
            <p>暂无相关文章。</p>
        {% endfor %}
    {% endarchiveList %}
    

    This code avoids manual writing{% if archives %}...{% else %}of繁琐ness.

Points to note

  • Syntax is strict:All{% if %}tags must have corresponding{% endif %}Come to a close,{% elif %}and{% else %}It is not necessary.
  • Type matching:When comparing, make sure the variable types involved are compatible; otherwise, you may get unexpected results.
  • Line spacing control:In the template,ifLabels may introduce extra blank lines. If you need to control the output strictly, you canif/else/endifadd dashes in the start and end delimiters of-to remove the blank lines generated by the tags, for example{%- if condition -%}.

MasteredifThe use of tags, you can control the display of AnQiCMS website content more flexibly and intelligently, providing your visitors with a better browsing experience.


Frequently Asked Questions (FAQ)

1. Can IifNested statementsifIs this statement?Yes, AnQiCMS template engine fully supportsifnested statements. You can place a fullif/eliforelsestatement inside any block as neededif...endifStructure, to handle more refined logical judgments.

2. How to check if a string variable contains specific text?You can usecontainA filter to determine if a string variable contains a specific text. For example, to checkarchive.Titlewhether it contains “AnQiCMS”, you can write as follows:{% if archive.Title|contain:"AnQiCMS" %}This will returntrueorfalseThus, control the display of content.

3. If I need to judge multiple conditions, is it using multipleifOr is it goodifCombineand/orIs the operator good?In most cases, if multiple conditions are in parallel relationships (i.e., they all act on the same judgment object, such asarchive.Flag == 'h' and archive.Views > 1000), then use oneifCombineandororOperators will be more concise and efficient. If these conditions are hierarchical or require different code blocks to be executed based on different conditions, then useif/elif/elseThe structure will be clearer. Avoid writing overly long and complex single conditional expressions to maintain readability.

Related articles

How to prevent content scraping on the front end in AnQiCMS, such as displaying watermarks or interference codes?

Protect Originality: AnQiCMS intelligent strategy for front-end content collection prevention In the era of explosive Internet content, the value of original content is becoming more and more prominent, but it also faces the risk of malicious collection.The hard work we put into writing and carefully designed images can be stolen in an instant by others, not only infringing on the creators' labor成果, but also potentially affecting the website's SEO performance and brand image.How can we effectively protect our digital assets?AnQiCMS (AnQiCMS) provides a very practical built-in solution to this issue

2025-11-09

How to automatically convert plain text URLs of articles in the AnQiCMS template to clickable hyperlinks?

In daily website content operations, we often need to mention some external links or URLs in articles, product descriptions, or single-page content.If these URLs appear only in plain text, visitors will not be able to click and jump directly, which will undoubtedly affect the user experience, and may even cause some important information to be ignored.AnQiCMS as a powerful content management system, provides a simple and efficient way to solve this problem, making your content more vivid and interactive.AnQiCMS uses a template engine syntax similar to Django

2025-11-09

How to implement multi-condition filtering display on the article list page with the `archiveFilters` tag of AnQiCMS?

It is crucial to provide users with a convenient and accurate content search experience in website operation.As the content of the website becomes richer, simple classification or keyword search is often not enough to meet the personalized needs of users.At this time, the multi-condition filtering function on the article list page is particularly important.For AnQiCMS users,巧妙利用 `archiveFilters` tag can easily achieve this goal, making your article list page instantly possess powerful filtering capabilities.

2025-11-09

How to dynamically generate page Title, Keywords and Description using `tdk` tag in AnQiCMS template?

In today's internet environment where content is exploding, Search Engine Optimization (SEO) is crucial for a website's visibility.And the Title (title), Keywords (keywords), and Description (description) on the website page, which we commonly call TDK, are key factors for search engines to understand page content, decide whether to display it to users, and whether users will click.In AnQiCMS, a content management system designed specifically for small and medium-sized enterprises and content operation teams, dynamically generating these TDK information is to enhance the website

2025-11-09

How to build and display the breadcrumb navigation of the current page using the `breadcrumb` tag in AnQiCMS?

In website operation, breadcrumb navigation (Breadcrumb Navigation) is an important element to enhance user experience and website structure clarity.It not only helps visitors quickly understand the position of the current page in the website hierarchy, but also effectively assists search engines in understanding the relationship between website content, and has a positive effect on SEO optimization.For AnQiCMS users, building and displaying breadcrumb navigation is a very convenient operation, thanks to the powerful template tags built into AnQiCMS.### Understand AnQiCMS's

2025-11-09

How to customize parameters in the AnQiCMS backend and display them in the front-end template?

During the operation of a website, we often encounter such needs: standard content fields (such as title, content, publication time) can no longer meet the needs of personalized display.For example, a product detail page may need to display "production dateAnQiCMS as a flexible enterprise-level content management system fully considers these customized needs.

2025-11-09

How to implement scheduled publishing of articles in AnQiCMS to ensure that content is visible on the front page at specified times?

As a content operator, we know that in the age of information explosion, the timing of content release often determines its dissemination effect.In order to coordinate with market activities, maintain a stable update frequency, or publish important announcements at specific times, a function that can accurately control the publication time is indispensable.AnQiCMS (AnQi Content Management System) is well-versed in this, providing us with a simple and powerful scheduling mechanism to ensure that every meticulously prepared article is presented to the reader at the most appropriate time.Use AnQiCMS for timed publishing

2025-11-09

How to iterate over an array or slice in AnQiCMS template and loop through its elements?

In the AnQi CMS template world, dynamically displaying content is the key to building an active and feature-rich website.Whether it is an article list, product display, navigation menu, or image gallery, we need a mechanism to traverse the data set and display each element on the page.Fortunately, the template engine of Anqi CMS provides an intuitive and easy-to-use loop structure, allowing us to easily achieve this goal.

2025-11-09