How to implement conditional (if/else) dynamic display of content and layout in a template?

Calendar 👁️ 91

In website operation and front-end development, we often need to flexibly display content or adjust the page layout according to different situations. This dynamic change capability is exactly what the conditional judgment tag in AnQiCMS (AnQiCMS) template offers.if/elseThe core value lies here. The Anqi CMS template engine is designed to be simple yet powerful, allowing us to set logic on the page like writing program code, making the website content show endless possibilities.

The dynamic beauty of AnQi CMS template: Understandingif/else

AnQi CMS uses a template engine syntax similar to Django or Blade, which means you can use double curly braces{{ 变量 }}Output data by using single curly braces and percent signs{% 标签 %}Define logical control, such as the conditional judgment we are going to delve into today.This design allows the template to efficiently render data and achieve complex dynamic interactions without delving into backend code.

Condition judgment label, namely{% if %}/{% elif %}/{% else %}and{% endif %}It is the cornerstone of dynamic content and layout. Its basic idea is: if a condition is true, execute a piece of code;Otherwise, execute another block of code. In this way, we can precisely control the display of each element on the page.

Basic conditional judgment structure

The simplest condition is{% if 条件 %}...{% endif %}. For example, you might want to check if a variable exists or is not empty:

{% if someVariable %}
    <p>这个变量有值:{{ someVariable }}</p>
{% endif %}

When dealing with more complex situations{% elif %}(short for else if) and{% else %}they come into play. They allow you to chain multiple conditions and provide a default display scheme when all conditions are not met:

{% if user.is_admin %}
    <p>欢迎,管理员!</p>
{% elif user.is_vip %}
    <p>欢迎,尊贵的VIP用户!</p>
{% else %}
    <p>欢迎,普通用户!</p>
{% endif %}

In conditions, we can make various types of judgments, for example:

  • number comparison: {% if item.Id == 10 %}/{% if count > 0 %}
  • String comparison: {% if item.Title == "最新新闻" %}(Note that strings must be enclosed in quotes)
  • Boolean value judgment: {% if item.IsRecommended %}/{% if not item.HasChildren %}
  • Combined conditions:Useand/or/notTo connect multiple judgment conditions, for example{% if user.is_logged_in and user.is_vip %}

Practical Application: Bring the Website to Life

Masteredif/elseFundamentals, let's take a look at its practical application scenarios in Anqi CMS templates, these scenarios can significantly improve the user experience and management efficiency of the website.

  1. Dynamically display/hide navigation menu itemsIn website navigation, sometimes we want certain menus to be visible only to specific users, or to hide the dropdown menu when there are no subcategories. For example, you can check if a navigation item has a submenu:

    {% navList navs %}
        {% for item in navs %}
            <li class="nav-item {% if item.IsCurrent %}active{% endif %}">
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                {% if item.NavList %} {# 检查是否存在子导航 #}
                    <ul class="submenu">
                        {% for subItem in item.NavList %}
                            <li><a href="{{ subItem.Link }}">{{ subItem.Title }}</a></li>
                        {% endfor %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    {% endnavList %}
    

    Here pass{% if item.NavList %}Determine whether the current navigation item contains a sub-navigation list, thereby deciding whether to render the HTML structure of the submenu.

  2. Flexible layout of the article detail page.On an article or product details page, the content may include images, videos, or specific attributes. Useif/elseYou can adjust the page layout based on the presence of this content. For example, an image is displayed only when the article has a thumbnail:

    {# 假设这里是文章详情页面的某个区域 #}
    {% archiveDetail archiveInfo with name="Content" %} {# 获取当前文章的详情数据 #}
    {% if archiveInfo.Thumb %} {# 如果文章有缩略图 #}
        <div class="article-thumb">
            <img src="{{ archiveInfo.Thumb }}" alt="{{ archiveInfo.Title }}">
        </div>
    {% endif %}
    <h1 class="article-title">{{ archiveInfo.Title }}</h1>
    <div class="article-content">
        {{ archiveInfo.Content|safe }}
    </div>
    {% endarchiveDetail %}
    

    By{% if archiveInfo.Thumb %}Check if the thumbnail exists, avoid displaying a broken placeholder when there is no image, making the page look more professional.

  3. List page empty state handlingWhen your article list, product list, or search results have no content, displaying a friendly prompt instead of a blank page can greatly enhance user experience. AnQi CMS'sforLoop tag自带{% empty %}Block, this is the elegant way to handle empty states, it is similar toif/elseThe "else" branch:

    {% archiveList archives with type="page" limit="10" %}
        {% for item in archives %}
            {# 显示文章列表项的代码 #}
            <div class="list-item">
                <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
                <p>{{ item.Description }}</p>
            </div>
        {% empty %} {# 如果archives列表为空,则执行这里的内容 #}
            <p class="no-content">抱歉,当前暂无内容可显示。</p>
        {% endfor %}
    {% endarchiveList %}
    
  4. Display content based on custom fieldsAnQi CMS supports powerful custom content model functionality. This means you can add as many custom fields as you like for articles, products, and so on. Throughif/elseYou can display content dynamically based on the values of these fields. For example, if a product has a 'Special Price' field, it will only display the special price information when it is true:

    {% archiveParams params with sorted=false %} {# 获取文章的自定义参数,使用无序map方便直接访问 #}
    {% if params.is_special_offer and params.is_special_offer.Value == "true" %} {# 假设自定义字段名为is_special_offer,且值为字符串"true" #}
        <span class="special-offer">特价优惠中!</span>
    {% endif %}
    {% if params.product_video and params.product_video.Value %} {# 假设有产品视频字段 #}
        <div class="product-video">
            <video src="{{ params.product_video.Value }}" controls></video>
        </div>
    {% endif %}
    {% endarchiveParams %}
    

    Here we show how to display specific promotional text or video players based on custom fields.is_special_offerandproduct_videoBased on the value, it determines whether to display specific promotional text or video players.

  5. Intelligent display of pagination componentsPage navigation is only meaningful when the content needs to be displayed on multiple pages. If there is only one page of content, there is no need to display pagination. This can also be achieved byif/elseeasily implement:

    {% pagination pages with show="5" %}
        {% if pages.TotalPages > 1 %} {# 只有当总页数大于1时才显示分页 #}
            <nav class="pagination-nav">
                <ul>
                    {# 分页链接,如首页、上一页、数字页码、下一页、尾页 #}
                    {% if pages.FirstPage %}<li><a href="{{pages.FirstPage.Link}}">首页</a></li>{% endif %}
                    {% if pages.PrevPage %}<li><a href="{{pages.PrevPage.Link}}">上一页</a></li>{% endif %}
                    {% for item in pages.Pages %}
                        <li {% if item.IsCurrent %}class="active"{% endif %}><a href="{{item.Link}}">{{item.Name}}</a></li>
                    {% endfor %}
                    {% if pages.NextPage %}<li><a href="{{pages.NextPage.Link}}">下一页</a></li>{% endif %}
                    {% if pages.LastPage %}<li><a href="{{pages.LastPage.Link}}">尾页</a></li>{% endif %}
                </ul>
            </nav>
        {% endif %}
    {% endpagination %}
    

    By{% if pages.TotalPages > 1 %}Determine the total number of pages, ensuring pagination navigation only appears when necessary.

Tip: **Practice** of template development.

In usingif/elseWhen developing templates with logical tags, please pay attention to the following points, which will help you build a more robust and easier to maintain website:

  • Syntax must be rigorous: {% if %}Must be with{% endif %}Pairwise, {% elif %}and{% else %}It is optional. Additionally, tag names and variable names are strictly case-sensitive.
  • Note the data type:It is important to understand the data type of variables when making conditional judgments. For example, if a field stores a number but you compare it as a string in the template ("10"instead of10), may lead to misjudgment.
  • Make good use of|safeFilter:When you output content that includes HTML code in a template (such as the main text of an article), in order to prevent the HTML from being escaped and displayed as source code, you must use|safeFilter, for example{{ archiveInfo.Content|safe }}.
  • Keep the code tidy:Reasonable indentation and comments can make your template code more readable, especially in complexif/elsenested structures.

By flexibly using the conditional judgment tags in the Anqi CMS template, you can easily control the dynamic display and layout adjustment of website content, providing users with a more personalized and intelligent browsing experience.

Frequently Asked Questions (FAQ)

Q1: Why my{% if %}The condition seems not to be working, the content is always displayed or not displayed?A1: There are usually several reasons. First, please check whether the variable names in the conditional statements are spelled correctly, including the case.Secondly, confirm whether the variable indeed contains the value you expect, or whether it does not exist at all (null,nil)。Sometimes, a mismatch in data types within a condition may lead to unexpected results, such as comparing numbers with strings. Additionally, please check yourif/elif/elseandendifAre the tags paired correctly, are there any missing or extra tags?

Q2: I want to{% if %}judge multiple conditions in a statement, how should I write it?A2: The Anqi CMS template engine supports usingand/orandnotlogical operators to combine multiple conditions. For example:

  • All conditions are met: {% if condition1 and condition2 %}
  • Any condition is met: {% if condition1 or condition2 %}
  • The condition is not met: {% if not condition %}You can also combine these operators and use parentheses to specify the precedence, for example:{% if (condition1 and condition2) or condition3 %}.

Q3: Can I dynamically display certain content or layout based on the current page URL?A3: Yes, although the document does not directly provide a tag to get the current URL, it is usually that CMS provides a global variable or method to get the current page URL, request parameters (query parameters). Assuming that Anqi CMS provides a namedurlParamsUse the global object to obtain URL parameters, you can judge like this:

  • {% if urlParams.category_id == "5" %}(Determine if the URL contains)category_id=5this parameter)
  • {% if urlParams.q %}(Determine if the URL contains the search keyword)q) For the complete URL path, you can check if there is something similarrequest.pathorcurrentPage.LinkSuch a variable to obtain, then combined with string comparison or filter for judgment.Specific global variables or functions, please refer to the latest template development manual of Anqi CMS or consult the community.

Related articles

How to customize the display template for specific articles, categories, or single pages to achieve personalized layout?

In website operation, providing exclusive display methods for specific content can significantly improve user experience and content marketing effectiveness.AnQiCMS (AnQiCMS) is well-versed in this field, providing flexible and diverse template customization features, allowing you to easily create a unique personalized layout for articles, categories, or single pages. The AnQi CMS realizes personalized template customization in two main ways: one is to follow specific **template file naming conventions**, the system will automatically identify and apply;Secondly, it is manually specified in the background management interface to use a custom template file.--- ### One

2025-11-08

How to modularize the header, footer, and other common parts in a template and reference them on each page to display uniformly?

In website operation, maintaining the consistency and efficient management of the website pages is the key to improving user experience and operational efficiency.For AnQiCMS (AnQiCMS) users, modularizing the header, footer, navigation bar, and other common parts not only ensures consistency in the overall visual style of the website but also greatly simplifies the maintenance and update work in the future.Strong and flexible template system provided by AnqiCMS, allowing you to easily achieve this goal.### Understanding AnQiCMS Template Architecture AnQiCMS template files are usually stored in

2025-11-08

What page adaptation modes are supported by AnQiCMS templates, and how to select and implement responsive display?

In the multi-screen era, users access websites through various devices, which has become the norm.To ensure that the website can provide a smooth and friendly experience on any device, page adaptation has become an indispensable part of website construction.AnQiCMS (AnQi Content Management System) fully considers this requirement, providing a variety of flexible template adaptation modes to help users easily cope with display challenges on different devices.

2025-11-08

How to use Django template engine syntax to display variables and logic structures?

AnQiCMS (AnQiCMS) uses a template engine syntax similar to Django in template creation. This design philosophy aims to provide content operators and developers with a powerful and easy-to-use tool, allowing them to more flexibly control the display of website content.By mastering this template syntax, you can easily display dynamic data on the website front end and control the presentation logic of content based on specific conditions.### One, the core composition of template syntax: variables and logical structures The template syntax of AnQi CMS mainly consists of two major parts

2025-11-08

How to loop through a list of data in a template and display it (using for loop), supporting counting and reversing?

In Anqi CMS template, efficiently displaying list data is an indispensable part of website content operation.Whether it is to display the latest articles, product lists, category directories, or customized data sets, flexible looping through these data and fine-grained control can greatly enhance the performance and user experience of the website.The Anqi CMS provides a powerful and easy-to-use template engine, its `for` loop tag is rich in features, supporting not only basic iteration but also easily implementing counting, reversal, and more advanced operations.### Core Concept: `for`

2025-11-08

How to avoid extra blank lines when template logical tags (such as if, for) are rendered on the page?

When developing templates in AnQiCMS, we often find that even though the template code itself looks neat, the final rendered HTML page may still contain some unexpected blank lines.These blank lines do not affect the page function, but may make the HTML source code look less tidy, and even in some extreme optimization scenarios, it may bring a slight increase in file size.For users who pursue code aesthetics and concise output, how to effectively avoid these redundant blank lines is a topic worth discussing.

2025-11-08

How to define and call the `macro` tag in AnQiCMS template to display reusable code blocks?

AnQiCMS provides a flexible and powerful template system, making the display of website content efficient and beautiful.In template development, in order to enhance the reusability and maintainability of code, we often encounter the need to encapsulate a commonly used code snippet so that it can be called in different places.This is when the `macro` tag becomes the key tool to achieve this goal.It allows us to define reusable code blocks, like functions in programming languages.Why do we need the `macro` tag?

2025-11-08

How to optimize page layout and content display by using the template inheritance (`extends`) tag?

In AnQiCMS, templates are the foundation for building the appearance and layout of a website.A well-designed template not only makes the website look professional and beautiful, but also greatly enhances the efficiency of content operation and the convenience of website maintenance.Among many powerful template tags, the `extends` (template inheritance) tag is undoubtedly one of the key tools for optimizing page layout and content display.It can help us build a unified and flexible website structure, making content operation and frontend development more effortless.### Understanding `extends`: The core of template inheritance `extends`

2025-11-08