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

Build a vibrant website in AnQiCMS, content management is not just about publishing information, but also about how to intelligently present these information.Imagine if your website could flexibly adjust the display style based on the actual data, such as showing images when available, or displaying alternative text when there are none; recommending related articles when available, or giving a friendly prompt like 'No related content available' when there are none. This would greatly enhance the user experience and make the website look more professional and smooth.

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

Foundations of variable existence judgment:iftags

In AnQiCMS template syntax, the most core judgment tool is.{% if 条件 %}Label.A variable itself can be used as a condition for judgment.TrueEnclosed in.ifThe content within the tag will be displayed. Conversely, if the variable isnilAn empty string, zero value, or empty array, the condition will be considered asFalse.

Let's see a common scenario: You want to display a thumbnail in the article detail page. But some articles may not have uploaded thumbnails. 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.ThumbIt is just a variable.If there is an image address, the image will be displayed; if not (such as an empty string), a prompt 'This article has no thumbnail' will appear.This method ensures both aesthetics and avoids blank or errors on the page caused by missing images.

English version: except for the simpleifandelse, you can also use{% elif 条件 %}to handle more complex judgment chains, which allows you to handle different situations separately.

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

Processing lists and empty data sets:for...emptythe elegant way

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

emptyTag specifically used for processing.forThe object for iteration is empty (nilor an empty array) in the following situation. In this case, you do not need to write extra code.ifThe code to determine the length of a list can directly include a friendly "no content" prompt within 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, the titles and links will be displayed one by one; if no related articles are found, a prompt 'No related articles' will be displayed.This way makes the template structure clearer and the logic more focused.

Use filters for more refined variable checks

Exceptifandfor...emptyAnQiCMS 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 an empty string, zero value ornilit will display “Anonymous user”.

    whiledefault_if_noneIt is more accurate, it only occurs when the variable is strictlynilThis provides a default value only when time is specified, and does not take effect on empty strings or zero values. This is very useful in scenarios where it is necessary to distinguish between 'not existing' and 'existing 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 the letter “h” (representing headline or hot), if it does, display the “hot” tag.

  • dumpFilter:Understanding what data structures and specific values a variable contains is crucial 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 for debugging and should not be exposed to users in a production environment.

Dynamic content display in practical applications

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

  1. Dynamically display pictures and Banners:If there is a Banner image uploaded for the category or a single page, a carousel will be displayed; if not, a default placeholder image will be displayed or it will not be displayed.

    {% 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. Personalized 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, if 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 whether a variable exists and dynamically displaying content is the foundation for building flexible and 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 when different content needs to be presented based on specific conditions. This not only improves the operational efficiency of the website but also provides visitors with a smoother and more personalized browsing experience.