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

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.