How to use conditional judgment (if/else) tags to control the display logic of content in AnQiCMS templates?

Calendar 👁️ 74

In the development and maintenance of website templates, we often encounter the need to display or hide different content based on specific conditions.This dynamic content display logic is crucial for improving user experience, realizing personalized functions, and optimizing website structure.AnQiCMS (AnQiCMS) as a powerful content management system provides a flexible template engine, where conditional judgments (if/else) Tag is the core tool to achieve this goal.

The template engine syntax of Anqi CMS is similar to Django, which allows developers to use concise and intuitive tags to control the generation of page content.By cleverly using conditional judgments, we can make the website content smarter and more closely aligned with the actual access situation of users.

Master the basic conditional judgment syntax

In the Anqi CMS template, conditional judgment tags are used in the form of{% if ... %}and ends with{% endif %}End. This is the most basic usage. The content inside the parentheses will be displayed when the condition inside the brackets is true; otherwise, it will not.

For example, we may need to check if a variable exists or is empty. Suppose we are displaying the details of an article, and we only want to display it when the article title exists:

{% if archive.Title %}
    <h1>{{ archive.Title }}</h1>
{% endif %}

here,archive.TitleRepresents the article title. If the article title has a value, this<h1>the tag and title content will appear on the page; if the title is empty, then the entire<h1>The tag and its content will not be rendered.

Introducing the 'else' branch:if-else

At times, when a condition is not met, we need to provide an alternative to display different content. At this point,elsethe tag comes into play. It is withifTags used together to form a mutually exclusive logical branch:

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

In this example, if the article has a thumbnail (archive.ThumbIf there is a thumbnail of the article, it will be displayed; if not, a default thumbnail will be displayed.This ensures the integrity of the page layout, avoiding blank or style issues due to missing images.

Handling multiple conditions:if-elif-else

When we need to handle more than two conditions, instead of multiple mutually exclusive cases,elif(else if abbreviation) tag is particularly important.It allows us to check a series of conditions in order until we find the first one that meets the condition and execute the corresponding code block.If allifandelifif none of the conditions are met, the lastelseblock (if it exists) will be executed as the default case.

For example, in an article list, we might want to display different tags based on the article's “recommended attribute”Flag) to display different tags:

{% if item.Flag == 'h' %}
    <span class="flag-hot">热点</span>
{% elif item.Flag == 'c' %}
    <span class="flag-recommend">推荐</span>
{% elif item.Flag == 'f' %}
    <span class="flag-slide">幻灯</span>
{% else %}
    <!-- 其他文章不显示特殊标记 -->
{% endif %}

here,item.FlagIndicates the recommended attribute of the article (such as fromarchiveListTagging articles from the list. The system will check in sequence whether the article is a hot spot, recommended, or slideshow, and display the corresponding tags. If none of them, no special tags will be displayed.

The practice scenario of flexibly using conditional judgment

The power of conditional judgment lies in its ability to deeply integrate with the various tags and data models provided by Anqi CMS, enabling extremely flexible content control.

  • Hint when the list content is empty:When usingarchiveListorcategoryListWhen using the tag to obtain a data list, if the list is empty, we can useifthe statement to determine the length of the list variable to display the prompt 'No content' instead of leaving it blank. For example,{% if archives|length > 0 %}Then iterate through the list,{% else %} <div>暂无相关文章</div> {% endif %}.

  • Current selected state of the navigation menu:While building the navigation menu,navListthe tags returned byitem.IsCurrentAn attribute is very useful. We can use it to determine whether the current navigation item is the page the user is visiting and add aactiveclass to highlight:

    <li {% if item.IsCurrent %}class="active"{% endif %}>
        <a href="{{ item.Link }}">{{ item.Title }}</a>
    </li>
    
  • Display features controlled by the system settings:Of Security CMSsystemTags can retrieve the global configuration information of the website. For example, we can determine if the website is closed and display the corresponding prompt page:

    {% system siteStatus with name="SiteStatus" %}
    {% if siteStatus == 0 %} {# 假设0代表关闭状态 #}
        {% system closeTips with name="SiteCloseTips" %}
        <div class="site-closed-message">
            {{ closeTips|safe }}
        </div>
    {% else %}
        <!-- 正常网站内容 -->
    {% endif %}
    

    Please note, the documenthelp-setting-system.mdin网站状态is for clarification当你选择为闭站状态下,用户将只会看到闭站提示信息。This indicates that the shutdown logic has already been handled at the system level, and the template level may be more used for judgment of other custom system parameters.

  • Custom field personalized display:ByarchiveDetailorcategoryDetailThe custom field obtained can determine how to display it based on its existence or specific value. For example, if the product model has a custom field calledPrice:

    {% archiveDetail productPrice with name="Price" %}
    {% if productPrice and productPrice > 0 %}
        <p>价格: {{ productPrice }} 元</p>
    {% else %}
        <p>价格: 询价</p>
    {% endif %}
    
  • Handle the availability of pagination links:InpaginationThe pagination object returned by the tag,pages.PrevPageandpages.NextPageCan be used to determine whether the previous page or next page exists, thus deciding whether to display the corresponding navigation button.

    {% if pages.PrevPage %}
        <a href="{{ pages.PrevPage.Link }}">上一页</a>
    {% else %}
        <span class="disabled">上一页</span>
    {% endif %}
    

Pay attention to the notes when writing conditional judgments

When writing conditional judgments, there are some tips that can help us write clearer and more efficient code:

  1. Be clear about the end tag:Every one{% if %}must have corresponding{% endif %}. If usedeliforelse, they must beifandendifbetween.
  2. Use logical operators:You can useand/or/notetc. logical operators to combine more complex conditions, such as{% if user.IsLoggedIn and user.IsAdmin %}.
  3. Variable existence judgment:Simply place the variable name inifthe statement, you can judge whether the variable exists and is not empty (for strings, numbers, lists, etc.). For example,{% if archive.Content %}it will be inarchive.ContentTrue when not empty.
  4. Precise comparison:You can use==(equal to),!=(Not equal),<(Less than),>(greater than),<=(less than or equal to),>=Comparison operators such as (greater than or equal to).
  5. Remove extra spaces:Use within conditional tags.{%-or-%}You can remove whitespace before or after the tag line, which is very useful for generating neat HTML code, especially when loop or conditional statements may introduce additional newline characters. For example:{%- if condition -%}.

By flexibly using the conditional judgment tags in the Anqi CMS template, we can create a responsive, feature-rich, and more intelligent website for content display.This has improved the professionalism of the website and also brought visitors a better browsing experience.


Frequently Asked Questions (FAQ)

1. What types of operators can I use in conditional statements?

You can use a variety of operators in conditional statements in AnQi CMS. In addition to the equality operators mentioned earlier,==Not equal!=) greater than (>) less than (<In addition to comparison operators, you can also use logical operators, such asand(Logical AND),or(Logical OR) andnot(Logical NOT) to combine or negate conditions. For example,{% if item.Views > 100 and item.Flag == 'h' %}In addition, you can even perform simple arithmetic operations in conditional judgments, such as{% if item.Price * item.Quantity > 500 %}.

2. How to apply different styles to different items in a loop?

InforIn a loop, you can use conditional judgments combined with the properties of the loop variable to dynamically apply styles. For example,forloop.CounterYou can get the current loop index (starting from 1),forloop.RevcounterYou can get the remaining number of loop iterations. You can add the first item in the loop like thisactiveClass:

{% for item in archives %}
    <div class="list-item {% if forloop.Counter == 1 %}active{% endif %}">
        {{ item.Title }}
    </div>
{% endfor %}

You can also combine the properties of the data itself, such asitem.IsCurrentoritem.StatusTo judge, apply different CSS classes based on different values.

What will happen if the variable referenced in the conditional judgment does not exist or is empty?

In the Anqi CMS template, when you areifIn a statement where a variable is directly referenced that does not exist or exists but has an empty value (such as an empty string, a number 0, nil, an empty list, or an empty object), the condition will be evaluated as false (falseThis is a convenient feature, as it allows you to safely check for the existence of data without causing template rendering errors. For example,{% if archive.Author %}only

Related articles

How to implement pagination for document lists in AnQiCMS and support custom page number quantities?

AnQiCMS document list pagination and custom page number settings: Make your content management more efficient Imagine, when your website content becomes rich, with thousands of articles, products, or news lists neatly arranged, if you cannot organize and display them effectively, users may feel at a loss.A good pagination mechanism not only improves user experience and helps visitors quickly find the information they need, but is also an important aspect of SEO optimization.

2025-11-07

How to call and display friend links in AnQiCMS templates?

Friendship links, as part of the website content ecosystem, not only help to improve search engine rankings and optimize website weight, but also provide users with more navigation to related resources.In AnQiCMS, managing and displaying friend links is a direct and flexible task, even if you do not have a deep programming background, you can easily achieve it. ### Backend Management: Easily Configure Friend Links In the AnQiCMS backend management interface, you will find the friend link settings under the "Function Management" menu.

2025-11-07

How to implement pagination and like function in AnQiCMS comment list?

The Anqi CMS plays a crucial role in content operation, where user interaction is an important factor in enhancing website activity. The comment function, along with its配套 pagination display and like function, is undoubtedly the key to achieving this goal.Benefiting from AnQiCMS's flexible template engine and rich built-in tags, we can relatively easily add these features to the articles or products of the website. ### 1.The basic enablement and configuration of the comment function Firstly, ensure that the website's comment function is enabled.

2025-11-07

How to display the Tag tag list and corresponding documents of articles in AnQiCMS template?

In AnQi CMS, the organization and display of content is diverse, and the Tag feature of the article provides users with flexible keyword association and content discovery paths.No matter if you want to display related tags on the article detail page or create a page that aggregates content with specific tags, Anqi CMS provides intuitive and powerful template tags to meet these needs. We will explore together how to effectively display the Tag tag list and its corresponding documents in the AnQiCMS template.

2025-11-07

How to use the (for) loop tag in AnQiCMS template to traverse and display the content list?

Efficiently using the `for` loop tag in AnQiCMS templates to display content lists is an indispensable core skill for building dynamic websites.By flexibly using the `for` loop, we can easily traverse various types of data collections and display them in a customized style on the website page, whether it is a news list, product display, category navigation, or any other repetitive content block, the `for` loop can help you a lot.

2025-11-07

How to correctly format timestamps in AnQiCMS templates so that content is displayed as needed?

In the daily operation of website content, time information plays a vital role.No matter the publication date of the article, the launch time of the product, or the latest update of the content, these time points directly affect users' perception and trust in the information.However, in the templates of content management systems, we often encounter dates stored in the form of "timestamps", which are precise but not intuitive.How should we correctly format these timestamps in the AnQiCMS template so that the content can be displayed in the way we expect?

2025-11-07

How to define and use variables in AnQiCMS templates to optimize the display and management of content?

In AnQi CMS, flexibly using template variables is the key to optimizing website content display and management efficiency.It not only makes your website content more dynamic, but also greatly improves the maintainability and reusability of the template.This article will delve into how to define and use variables in AnQiCMS templates, as well as how to better present content through these techniques. ### Variables: The Foundation of Living Content Imagine how cumbersome it would be if every title, every paragraph on a website had to be manually modified.The introduction of variables is to solve this pain point

2025-11-07

How to reuse common code snippets through the `include` tag in AnQiCMS templates to optimize the display structure?

When building and managing websites, improving efficiency and maintaining code neatness is the goal pursued by every operator.AnQiCMS (AnQiCMS) as an efficient content management system, provides powerful template functions, among which the `include` tag is the tool to achieve this goal.It allows us to abstract out repeated code snippets from the website, forming independent modules, and then referencing them where needed, greatly optimizing the template structure and subsequent maintenance work.

2025-11-07