How can you determine if a variable exists in a template and dynamically display content based on the result?

Calendar 👁️ 85

Build a vibrant website on AnQiCMS, content management is not just about publishing information, but also about how to intelligently present this information.Imagine if your website could flexibly adjust the display style based on the actual data, such as displaying an image if there is one, and displaying a substitute text if there isn't;If there is relevant content, recommend it; if not, kindly prompt 'No relevant content', which will greatly improve user experience and make the website look more professional and smooth.

The key to realizing this intelligent dynamic display lies in how to determine if a variable exists in the template or if it contains valuable content.AnQiCMS uses a template syntax similar to Django, which provides us with powerful conditional judgment capabilities, allowing the website content to always display the most appropriate information like a considerate guide.

The foundation of variable existence judgment:ifTag

In AnQiCMS template syntax, the most core judgment tool is{% if 条件 %}Label. A variable itself can be used as a condition for judgment.If the variable has a value (for example, a non-empty string, non-zero number, non-empty array, or object), then the condition will be considered to beTruewrapped inifthe content within the tag will be displayed. Conversely, if the variable isnilAn empty string, zero value, or empty array, the condition would be consideredFalse.

Let's look at a common scenario: You want to display a thumbnail on the article detail page. But some articles may not have uploaded a thumbnail. In this case, you can useifto judge:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}" class="article-thumb">
{% else %}
    <p>该文章暂无缩略图。</p>
{% endif %}

here,archive.Thumbis a variable. If it has an image address, the image will be displayed;If there is none (such as an empty string), the prompt "This article has no thumbnail" will appear.This method ensures beauty and avoids blank or errors on the page caused by missing images.

In addition to simpleifandelseyou can also use{% elif 条件 %}Handle more complex judgment chains, which allows you to handle various situations separately.

{% if user.IsVIP %}
    <p>欢迎尊贵的VIP用户,享受专属内容!</p>
{% elif user.IsLoggedIn %}
    <p>您已登录,欢迎回来!</p>
{% else %}
    <p>请登录或注册,体验更多功能。</p>
{% endif %}

Handle lists and empty data sets:for...emptyThe Art of Elegance

When you need to display a list, such as an article list, comment list, or friend link, you may encounter an empty list. AnQiCMS template provides a very elegant solution: {% for ... %}{% empty %}{% endfor %}Combined tag.

emptyThe tag is specifically used to processforThe scenario when the looping object is empty (nilor an empty array) occurs. In this way, you do not need to write extra code.ifThe code to judge the length of a list can directly include a friendly "no content" prompt in the loop structure.

For example, in the related articles section, you can use it to avoid displaying an empty list:

<div class="related-articles">
    <h3>相关文章推荐</h3>
    {% archiveList archives with type="related" limit="5" %}
        {% for item in archives %}
            <a href="{{ item.Link }}" title="{{ item.Title }}">{{ item.Title }}</a>
        {% empty %}
            <p>暂无相关文章。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

This code will first try to retrieve 5 related articles. If found, it will display their titles and links one by one.If no related articles are found, the prompt "No related articles" will be displayed.This way makes the template structure clearer and the logic more focused.

Use a filter for more precise variable checking

exceptifandfor...empty,AnQiCMS rich filters (filters) can also help us perform more detailed variable checks and dynamic content display.

  • defaultanddefault_if_noneFilter:When you want a variable to display a preset default text instead of a blank when it has no value,defaultThe filter comes into play.

    <p>发布者:{{ archive.Author|default:"匿名用户" }}</p>
    

    Here, ifarchive.Authorfor empty strings, zero values, ornilit will display "Anonymous User".

    Anddefault_if_noneIt is more accurate, it only applies when the variable is strictly equal tonilOnly when providing a default value does it not take effect on empty strings or zero values. This is very useful in scenarios where it is necessary to distinguish between 'non-existent' and 'exists but empty'.

    <p>联系电话:{{ contact.Cellphone|default_if_none:"未提供" }}</p>
    
  • lengthFilter:Sometimes, we not only need to determine if a variable exists, but also need to know its length or the number of elements it contains.lengthThe filter can return the length of a string, array, or key-value pair.

    {% if archive.Description|length > 50 %}
        <p>{{ archive.Description|truncatechars:100 }} <a href="{{ archive.Link }}">阅读更多</a></p>
    {% else %}
        <p>{{ archive.Description }}</p>
    {% endif %}
    

    This code determines the length of the article description, if it exceeds 50 characters, it truncates the first 100 characters and adds a 'Read more' link; otherwise, it displays the description in full.

  • containFilter:If you need to determine whether a string or array contains a specific keyword or value,containthe filter is very useful.

    {% set flags = archive.Flag|split:',' %} {# 假设Flag是逗号分隔的字符串,先拆分成数组 #}
    {% if flags|contain:'h' %}
        <span class="flag-hot">热门</span>
    {% endif %}
    

    here, we determine the article'sFlagDoes the attribute contain 'h' (representing headline or hot), if it does, display the 'hot' tag.

  • dumpFilter:It is crucial to understand what data structures and specific values a variable contains during template development and debugging.dumpThe filter can print the internal structure, type, and value of any variable in detail, which is very helpful for troubleshooting.

    <p>文章数据结构:{{ archive|dump }}</p>
    

    Of course, this is usually used only for debugging and should not be exposed to users in production environments.

Dynamic content display in practical applications.

By flexibly using these judgment logic and filters, you can make your AnQiCMS website more intelligent:

  1. Dynamically display pictures and banners:If the category or single page has uploaded a Banner image, it will display a carousel; if not, it will display a default placeholder image or not display.

    {% categoryDetail bannerImages with name="Images" %}
    {% if bannerImages %}
        {% set pageBanner = bannerImages[0] %} {# 假设只需要第一张图作为背景 #}
        <div class="category-banner" style="background-image: url('{{ pageBanner }}');">
            <!-- Banner 内容 -->
        </div>
    {% else %}
        <div class="category-banner-placeholder">
            <p>该分类暂无精美背景图。</p>
        </div>
    {% endif %}
    
  2. Customized navigation menu:Dynamically adjust the navigation menu items based on the user's login status, VIP status, or the existence of specific content (such as whether the comment feature is enabled).

    {% navList navs %}
        {% for item in navs %}
            <li>
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                {% if item.NavList %} {# 判断是否存在子导航 #}
                    <ul>
                        {% for subItem in item.NavList %}
                            <li><a href="{{ subItem.Link }}">{{ subItem.Title }}</a></li>
                        {% endfor %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    {% endnavList %}
    
  3. Customized contact information:On the footer or contact us page, icons and links are dynamically displayed according to the contact information set in the background (for example, whether WhatsApp has a value).

    {% contact contactWhatsApp with name="WhatsApp" %}
    {% if contactWhatsApp %}
        <a href="https://wa.me/{{ contactWhatsApp }}" target="_blank" rel="nofollow">
            <img src="/static/images/whatsapp-icon.png" alt="WhatsApp">
            <span>{{ contactWhatsApp }}</span>
        </a>
    {% endif %}
    

Summary

In AnQiCMS templates, determining if a variable exists and dynamically displaying content is the foundation for building flexible, user-friendly websites. By masteringif/for...emptytags as welldefault/length/containFilters that allow the website to maintain elegance and intelligence when data is incomplete or needs to be presented differently based on specific conditions. This not only improves the operational efficiency of the website but also brings a smoother and more personalized browsing experience to your visitors

Related articles

How to implement showing or hiding part of the content based on user group permissions (such as VIP exclusive content)?

In website operation, providing differentiated content services based on user identity is a common strategy to enhance user experience and achieve content monetization.AnQiCMS (AnQiCMS) with its flexible user group management and VIP system, can help us easily implement content display or hide based on user permissions.This article will delve into how to use this feature of Anqi CMS to create exclusive VIP content for your website or display different information based on user level.

2025-11-09

How to use the `archiveList` tag to sort and display the article list by views or publication time?

How to efficiently display and organize content in website operation often directly relates to user experience and the effectiveness of content dissemination.AnQiCMS provides a series of powerful and flexible template tags that allow content managers to easily control the display of articles.Today, let's talk about how to use the `archiveList` tag to sort and display the article list by views or publishing time.### Understanding the `archiveList` tag The `archiveList` tag is AnQiCMS

2025-11-09

How to include external static resource files (CSS, JS, images) in a template?

When using AnQiCMS to build a website, introducing styles (CSS), interactive scripts (JS), and images as static resources is the foundation for the website's aesthetics and functionality.Understand how to correctly introduce these files in the template, so that your website not only looks professional but also has rich functions and maintains efficient and stable operation.AnQi CMS with its concise and efficient architecture and flexible template engine makes it very intuitive to manage and introduce these resources.The AnQiCMS template system, especially in handling static resources, is very thoughtful

2025-11-09

How to display the filing number in the footer and generate a link to the filing official website?

In website operation, especially for mainland Chinese users, correctly displaying the website's ICP filing number is an important aspect of compliance.The record number is usually located at the footer of the website and will link to the Ministry of Industry and Information Technology's government service platform (beian.miit.gov.cn), convenient for users to query and verify.An enterprise CMS provides users with a convenient way to configure and display this information. Next, we will introduce step by step how to display the record number in the footer of your Anqi CMS website and generate a link to the record official website.### First Step

2025-11-09

How to control the display of different styles for odd and even rows in a table or list loop?

In web design and content presentation, in order to enhance the user reading experience and make the information presentation clearer, we often need to apply different styles to the odd and even rows in tables or lists.This visual distinction not only breaks the monotony of the content, but also significantly improves the readability of the data.In AnQiCMS, with its flexible and powerful template engine, achieving this effect is quite direct and convenient.

2025-11-09

How can you format a timestamp to display the publication date in a friendly date and time format?

In website operation, the content publication date is not just a time mark, it is also an important basis for visitors to obtain information timeliness.A clear and readable date format that can significantly improve user experience and make your website content appear more professional and considerate.However, in a powerful content management system like AnQiCMS, the publication date is usually stored in the database in the form of a "timestamp", which is usually a string of numbers that is difficult to understand directly.For example, you might see a number like `1609470335`

2025-11-09

How to customize the display of Banner Carousel images on the website homepage?

In website operation, the homepage Banner carousel image is an important component to attract visitors' attention and convey core information.AnQiCMS (AnQiCMS) understands this need and provides a flexible and convenient way for you to easily customize and display these key visual elements on the homepage of your website. ### Prepare: Manage Your Banner Image in the Background First, we need to make sure that the images used for the carousel have been uploaded and properly managed.The AnQi CMS usually provides a special "Banner Management" area in the background

2025-11-09

How to display a list of friendship links on the front page of the website?

In website operation, friendship links have always been an important means to enhance website authority, increase external traffic, and enhance user trust.If you are using AnQiCMS to manage your website and want to display a list of friend links on the frontend page, you will find that this process is surprisingly simple and efficient.AnQi CMS, with its simple design and powerful features, makes content management easy, and the display of friendship links is no exception.Next, let's take a look at how to display friend links in Anqi CMS.

2025-11-09