How to implement dynamic display of content and layout based on conditions (if/else) in the 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 ability of dynamic change is exactly what the conditional judgment tags in AnQiCMS template provide.if/else

Understanding the Dynamic Beauty of Anqi CMS Templateif/else

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

Conditional judgment tag, that is{% if %}/{% elif %}/{% else %}and{% endif %}It is the cornerstone for implementing dynamic content and layout.Its basic idea is: if a certain condition is true, execute a piece of code; otherwise, execute another piece of code.Through this method, we can precisely control whether each element on the page is displayed.

Basic conditional judgment structure

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

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

When dealing with more complex multiple cases,{% elif %}[else if abbreviation] and{% else %}They come into play. They allow you to check multiple conditions in a chained manner, and provide a default display scheme if none of the conditions are 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, such as:

  • 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/notConnect multiple judgment conditions, for example{% if user.is_logged_in and user.is_vip %}

Practical Application: Bring the website to life

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

  1. Display/Hide Navigation Menu ItemsIn the website navigation, sometimes we want some menus to be visible only to certain 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 through{% 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.In the article or product details page, the content may include images, videos, or specific properties. Useif/elseThe layout of the page can be adjusted based on the presence of this content. For example, the image will only be displayed when there is a thumbnail of the article:

    {# 假设这里是文章详情页面的某个区域 #}
    {% 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 %}
    

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

  3. Handling the empty state on the list page.When your article list, product list, or search results are empty, displaying a friendly prompt instead of a blank page can greatly enhance user experience. The Anqi CMS'sforLoop label is built-in{% empty %}Block, which is an elegant way to handle empty states, it is similar toif/elseThe "else" branch in it:

    {% 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 fieldsThe CMS supports powerful custom content model functionality. This means you can add an unlimited number of custom fields for articles, products, and more.if/elseYou can dynamically display content based on the values of these fields. For example, if a product has a 'Special Offer' field, the special offer information will only be displayed 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 player based on a custom fieldis_special_offerandproduct_videoby the value, to determine whether to display specific promotional text or video player.

  5. of the smart display of pagination componentsPage navigation is meaningful only when the content needs to be displayed over multiple pages. If there is only one page of content, pagination is not necessary. This can also be easily achieved:if/elseEasily implemented:

    {% 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 %}
    

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

Tip: **Practice** in template development.

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

  • Syntax should be rigorous: {% if %}Must be paired with{% endif %},{% elif %}and{% else %}Is optional. Both tag names and variable names are strictly case-sensitive.
  • Note the data type:It is important to understand the data type of a variable when making conditional judgments. For example, if a field stores a number, but you compare it as a string in the template ("10"Instead10May lead to misjudgment.
  • Use wisely|safeFilter:When you output content containing HTML code in a template (such as the main body of an article), in order to prevent the HTML from being escaped and displayed as the source code directly, 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.

Common Questions (FAQ)

Q1: Why my{% if %}It seems that the condition did not take effect, the content is always displayed or not displayed?A1: This usually has several reasons.Firstly, please check whether the variable names in the conditional statements are spelled correctly, including the case.nil)。Sometimes, a mismatch in data types within conditions can also lead to unexpected results, such as comparing numbers with strings. Additionally, please check yourif/elif/elseandendifLabel pairing is correct, are there any missing or extra labels.

Q2: I want to ask in a{% if %}How should I write multiple conditions in a statement?A2: The template engine of AnQi CMS 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 clarify the precedence, for example:{% if (condition1 and condition2) or condition3 %}.

Q3: Can I dynamically display some 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 common for CMS to provide a global variable or method to get the current page URL and request parameters (query parameters). Suppose Anqi CMS provides a namedurlParamsThe 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 search keywords)qFor a 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 available, it is recommended to refer to the latest template development manual of Anqi CMS or consult the community.