How to use conditional judgment logic in a template to control the display and hiding of content?

Calendar 👁️ 63

In the presentation of website content, we often need to decide according to different situations which information should be displayed to the visitors and which should be temporarily hidden.AnQiCMS (AnQiCMS) provides flexible template condition judgment logic, making content display and hide intuitive and efficient.By these judgments, you can easily implement personalized page layouts, content display under permission control, and adjustment of page elements based on data status, greatly enhancing the dynamicity and user experience of the website.

The Anqi CMS template system uses a syntax similar to the Django template engine, which makes the structure of conditional judgments clear and easy to understand. The core conditional judgment statement is{% if ... %}It allows you to check if a condition is true and execute the corresponding code block based on the result.

The conditional syntax in AnQi CMS: The cornerstone

The most basic conditional structure is{% if 条件 %} ... {% endif %}. When条件The expression evaluates to true,ifandendifthe content between will be displayed.

If you need to handle more complex logic, you can introduce{% elif 其他条件 %}and{% else %}.elifthat allows you to add more conditional branches, whileelseIt acts as the default handling when all conditions are not met.

{# 简单条件判断 #}
{% if archive.Id == 10 %}
    <p>这是ID为10的特别文章。</p>
{% endif %}

{# 包含多个分支的判断 #}
{% if user.is_admin %}
    <p>欢迎,管理员!</p>
{% elif user.is_vip %}
    <p>尊贵的VIP用户,您好!</p>
{% else %}
    <p>普通用户,请登录。</p>
{% endif %}

Here, 'condition' can be various expressions, including variables, comparison operations (such as==/!=/>/</>=/<=), logical operations (and/or/not),even some functions or filters return results.

Common application scenarios and practical examples

After understanding the basic syntax, let's see how to use these conditional judgments to control the display of content in actual AnQi CMS template development.

1. Based on whether a variable exists or is empty

This is one of the most commonly used scenarios. Often, we want to display related content only when certain data exists, such as when an article has a thumbnail, or when a system setting item is configured.In the Anqi CMS template, a variable that does not exist, is an empty string, or isnil,false, a zero (number), or an empty array/slice will be consideredfalse.

{# 判断文章是否有缩略图 #}
{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}"/>
{% else %}
    <span>此文章暂无缩略图。</span>
{% endif %}

{# 判断网站备案号是否配置 #}
{% system siteIcp with name="SiteIcp" %}
{% if siteIcp %}
    <p>备案号:<a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">{{ siteIcp }}</a></p>
{% else %}
    {# 不显示备案号区域 #}
{% endif %}

2. Based on a specific value for judgment

You may need to display different content based on the specific value of the variable. For example, whether to add a friend linkrel="nofollow"property, or display different text based on the current page language.

{# 友情链接根据后台设置决定是否添加nofollow #}
{% linkList friendLinks %}
    {% if friendLinks %}
        <ul>
            {% for item in friendLinks %}
                <li><a href="{{ item.Link }}" {% if item.Nofollow == 1 %} rel="nofollow" {% endif %} target="_blank">{{ item.Title }}</a></li>
            {% endfor %}
        </ul>
    {% endif %}
{% endlinkList %}

{# 根据系统语言显示不同内容 (假设您在后台设置了Language字段) #}
{% system currentLang with name="Language" %}
{% if currentLang == "zh-CN" %}
    <p>欢迎来到中文站!</p>
{% elif currentLang == "en-US" %}
    <p>Welcome to our English site!</p>
{% else %}
    <p>语言未知。</p>
{% endif %}

3. Logical Combination Judgment

When a single condition is not enough to express your needs, you can useand/orandnotto combine multiple conditions and build more complex logic.

{# 判断分类既有子分类,且子分类下有文章,才显示特定布局 #}
{% categoryList currentCategory with parentId="0" %} {# 获取当前分类,假设它是一个父级分类 #}
{% if currentCategory.HasChildren and currentCategory.ArchiveCount > 0 %}
    <h3>包含子分类和文章的模块</h3>
    {# ... 展示子分类和文章的复杂布局 ... #}
{% else %}
    <h3>普通分类模块</h3>
    {# ... 展示普通分类内容 ... #}
{% endif %}

{# 判断如果没有Logo图片,且网站名称不为空,则显示网站名称作为Logo替代 #}
{% system siteLogo with name="SiteLogo" %}
{% system siteName with name="SiteName" %}
{% if not siteLogo and siteName %}
    <h1>{{ siteName }}</h1>
{% elif siteLogo %}
    <img src="{{ siteLogo }}" alt="{{ siteName }}"/>
{% endif %}

4. Condition Judgment in Loops

InforIn loops, conditional judgments are very useful. For example, adding a special style to the first element in the loop or handling the case of an empty list.

{% archiveList archives with type="list" limit="5" %}
    <ul>
    {% for item in archives %}
        {# 为第一个列表项添加'active'类名 #}
        <li {% if forloop.Counter == 1 %}class="active"{% endif %}>
            <a href="{{ item.Link }}">{{ item.Title }}</a>
        </li>
    {% empty %}
        {# 如果archives列表为空,显示此内容 #}
        <li>暂无文章可显示。</li>
    {% endfor %}
    </ul>
{% endarchiveList %}

Hereforloop.CounterIt is a special variable that represents the current iteration count of the loop (starting from 1).{% empty %}The block is inforA special judgment executed when the loop iteration object is empty, which allows you to avoid the need for an independentif archivesjudgment.

5. Use filters to enhance conditional judgment

The Anqi CMS template provides a rich set of filters that can be combined with conditional judgments to achieve more refined control.For example, judge the length of a string, whether it contains a specific substring, etc.

{# 判断文章描述的长度,决定是否显示“阅读更多” #}
{% archiveDetail archiveDesc with name="Description" %}
{% if archiveDesc|length > 100 %}
    <p>{{ archiveDesc|truncatechars:100 }}...</p>
    <a href="{{ archive.Link }}">阅读更多</a>
{% else %}
    <p>{{ archiveDesc }}</p>
{% endif %}

{# 判断文章标题是否包含特定关键词,例如“促销” #}
{% archiveList archives with type="list" limit="3" %}
    {% for item in archives %}
        <li>
            {% if item.Title|contain:"促销" %}
                <span style="color: red;">【促销】</span>
            {% endif %}
            <a href="{{ item.Link }}">{{ item.Title }}</a>
        </li>
    {% endfor %}
{% endarchiveList %}

Optimization and注意事项

When using conditional judgment, there are several tips to help you keep the template tidy and efficient:

  • Keep it concise:Avoid overly complex nested conditions as it reduces the readability of the code.If the logic becomes very complex, consider whether it is possible to preprocess the data at the controller layer or break it down into smaller logic blocks.
  • Pay attention to whitespace:The template tag itself may introduce unnecessary

Related articles

How to display breadcrumb navigation on the page to enhance users' understanding of the content structure?

When we browse websites, we often see a line of text at the top or above the content area, clearly indicating the position of the current page within the overall website structure, like "Home > Product Center > Some Product Category > Some Product Detail" and so on.This is what we commonly refer to as 'Breadcrumb Navigation'.It can not only help users quickly understand the content hierarchy of the website, avoid getting lost, but also play an important role in user experience and search engine optimization (SEO).Aq CMS fully understands the importance of breadcrumb navigation

2025-11-08

How to build and display a multi-level navigation menu for a website?

Website navigation, like the skeleton and compass of a website, it guides visitors to explore the website content, and is the core of user experience and information architecture.A clear and accessible navigation menu that not only helps users find the information they need quickly, but is also crucial for search engine optimization (SEO).AnQiCMS (AnQiCMS) is well-versed in this, providing powerful and flexible navigation management features that allow you to easily build and display multi-level navigation menus.Next, we will delve deeper into how to build and display your website navigation step by step in Anqi CMS.--- ### One

2025-11-08

How to dynamically display SEO titles, keywords, and descriptions (TDK) on different pages?

In website operation, Search Engine Optimization (SEO) is a key element in enhancing website visibility.Among them, the page title (Title), keywords (Keywords), and description (Description), abbreviated as TDK, play a crucial role.They are not only the primary information that search engines understand the content of the page, but also an important factor in attracting users to click.In AnQiCMS (AnQiCMS), we can easily implement the dynamic display of TDK, allowing each page of the website to have appropriate and attractive TDK information

2025-11-08

How to display contact information on the page, such as phone number, address, etc.

The contact information of the website is an important part of establishing user trust and providing convenient services.Whether it is displaying a simple phone number at the bottom of the website or providing detailed addresses and social media links on the "Contact Us" page, Anqi CMS offers a flexible and efficient way to manage and present these key information.This article will delve into how to set up and display all the contact information on your website using Anqi CMS, ensuring that your customers can easily find you.### Backend Management:Unified setting your contact information In AnQi CMS

2025-11-08

How to iterate over list data in a template and display it one by one?

Managing and displaying content in Anqi CMS is one of its core advantages.When we need to display dynamic list data on the front end of a website, such as the latest articles, popular products, and content collections under categories, understanding how to efficiently iterate through these data in templates and display them one by one is an essential skill for website operators and template developers.The Anqi CMS template system adopts syntax similar to Django, which is intuitive and powerful, making the transformation of technical information and practical application extremely convenient.### Core Loop Syntax: `{% for %}`

2025-11-08

How to format timestamps and display them on the page as a readable date and time?

In website operation, the timeliness of content is often the key to attracting readers' attention.Whether it is the release date of the article or the update time of the product, these pieces of information, if presented in a clear and easy-to-understand manner on the page, will greatly enhance the user experience.However, you may find that the time information recorded by AnQiCMS backend, when directly called in the template, often appears as a long series of numbers, which is what we usually call a timestamp.These original timestamps are convenient for internal system processing, but they lack readability for ordinary users.It's lucky that

2025-11-08

How to set the recommendation attribute to affect the display priority of the front-end content when publishing a document?

How to effectively guide visitors to focus on key information when managing content in AnQi CMS, and enhance the visibility and interactivity of the content, is a common concern for operators.By setting the recommended properties of the document reasonably, we can finely control the display priority of the front-end content, thereby achieving this goal.This not only helps to optimize the user experience, but also better serves the overall operation strategy of the website.### Backend settings recommended attribute: clear content positioning When we publish or edit a document, the content editing interface of Anqi CMS provides a feature area named "Recommended Attribute".

2025-11-08

How to customize the document URL alias to optimize its display in browsers and search results?

In website operation, a URL (Uniform Resource Locator) is not only the address of the content, but also the first step for users and search engines to recognize the website.A clear, meaningful, and friendly URL alias that can greatly enhance the display effect of content in the browser and achieve better visibility in search results.AnQiCMS provides flexible and powerful features, allowing us to easily customize documents, categories, tags, and even the URL aliases of the page itself, thereby optimizing the overall performance of the website.Why is it important to use custom URL aliases?Firstly, for search engines

2025-11-08