How to determine if a variable (such as the article title) exists or is empty in a template and display a custom default value?

In website content management, ensuring the completeness and user experience is crucial.Sometimes, due to missing content or unassigned variables, blank areas or error messages may appear on web pages, which undoubtedly affects the professionalism of the website.The AnQiCMS template engine provides a flexible and powerful mechanism to help users elegantly handle these situations, ensuring the robust presentation of page content even if variables do not exist or are empty.

In AnQiCMS template design, we often encounter situations where we need to display a variable (such as article title, description, image URL, etc.).However, in practice, these variables may be missing for various reasons.This is when we need a method to determine their existence and provide a custom default value if necessary, to avoid the page looking empty or showing errors.

The basic approach to variable existence and null value judgment

AnQiCMS template engine adopts syntax similar to Django, which means we can make use ofifTags for conditional judgment. This is the most direct method to handle the existence or null value of a variable.

When we want to judge whether a variable (such asarchive.Title, i.e., the article title) has a value, we can use it directly.{% if 变量名 %}Such a structure. This judgment method checks whether the variable is a non-empty string, non-zero number, nonnil(Null Pointer) Object or non-empty collection. If the variable has actual content, the condition is true; otherwise, it is false.

For example, if you want to display a default prompt when the article title is empty:

{% if archive.Title %}
    <h1>{{ archive.Title }}</h1>
{% else %}
    <h1>暂无文章标题</h1>
{% endif %}

If you need to accurately determine whether a variable is an empty string, rather than simply "no value", you can explicitly compare it with an empty string:

{% if archive.Title == "" %}
    <h1>内容正在编辑中...</h1>
{% else %}
    <h1>{{ archive.Title }}</h1>
{% endif %}

Use a filter to elegantly set the default value

AlthoughifJudgment can solve the problem, but in some cases, Anqi CMS provides a more concise and elegant way to handle default variable values - that is to use filters. Among them,defaultanddefault_if_noneThese filters are the tools to meet this requirement.

defaultFilters are very practical. When a variable isnilWhen it is null pointer, empty string, or certain types of zero values (such as the number 0), it will output the default value you provided. This means you do not need to explicitly writeif-elseStructure, which can set a default content for possibly empty variables.

For example, set a default value for the article title:

<h1>{{ archive.Title|default:"未命名文章" }}</h1>

The meaning of this code is: ifarchive.TitleIf there is a value, display it; if not, display 'Unnamed Article'.

Another one isdefault_if_noneFilter. If you only need to targetnil(The case where a null pointer is set to a default value, but you want an empty string or zero value to be displayed, then)default_if_noneIt would be a more precise choice. In practice, since most content variables are stored as empty strings in the database if there is no value, thereforedefaultFilters are usually more general and commonly used.

For example, if you want to displayarchive.TitleWithnilthe default value but an empty string is also valid content:

<h1>{{ archive.Title|default_if_none:"标题信息缺失" }}</h1>

However, in the normal use of Anqi CMS, variables usually either have an explicit value or are empty strings,nilwhich is relatively rare, sodefaultThe filter is sufficient to handle the vast majority of scenarios.

Combined with specific scenarios: taking the article title as an example

Let's take an example of a common article detail page to see how to apply these skills in actual templates.Assuming we are designing an article detail template, we need to display the title, content, and thumbnail.

Firstly, obtaining the article detail data is usually througharchiveDetailLabel it and assign the result to a variable, for examplearticle:

{% archiveDetail article %}
    <div class="article-header">
        <h1>{{ article.Title|default:"【重要通知】本站最新动态" }}</h1>
        <p class="description">{{ article.Description|default:"本文暂无简介,敬请期待更多精彩内容!" }}</p>
    </div>

    <div class="article-image">
        <img src="{{ article.Thumb|default:"/static/images/default-thumbnail.webp" }}" alt="{{ article.Title|default:"默认图片" }}">
    </div>

    <div class="article-content">
        {% if article.Content %}
            {{ article.Content|safe }}
        {% else %}
            <p>文章内容正在创作中,请稍后访问。</p>
        {% endif %}
    </div>
{% endarchiveDetail %}

In this example:

  • Article titlearticle.TitleAnd descriptionarticle.DescriptionUsed directlydefaultFilter, when they are empty, they will display the specified default text.
  • Article thumbnailarticle.ThumbUsed similarlydefaultA filter that loads a preset default image when the image path is empty, preventing broken images from appearing on the page.
  • Article contentarticle.ContentDue to the possibility of containing complex HTML structures, here we useiftags to determine if they exist. If they exist, then through|safeThe filter outputs safely; if it does not exist, it displays a friendly prompt text.

By these methods, regardless of how the data in the backend content management system changes, our front-end page can maintain good display effects and provide users with a smooth and professional browsing experience.


Frequently Asked Questions (FAQ)

1. How to determine if a list (such as a related articles list) is empty, and display 'No content' when it is?Anqi CMS template engine'sforLoop tags are built-inemptyThe clause is specifically used to handle the case of an empty list. You do not need to use it extra.ifJudgment:

{% archiveList relatedArchives with type="related" limit="5" %}
    {% for item in relatedArchives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <li>暂无相关内容。</li>
    {% endfor %}
{% endarchiveList %}

2. If a variable containing an image link (such asarchive.LogoIs it possible to avoid displaying a broken image and provide a default image in the template?The simplest method is to usedefaultfilter. InsrcApply the filter directly in the property, specify the path to a default image accordingly.

<img src="{{ archive.Logo|default:"/public/static/images/default_logo.png" }}" alt="{{ archive.Title|default:"网站Logo" }}">

Make sure/public/static/images/default_logo.pngIt is the actual default image path existing on your website.

3. Can I display a more complex HTML structure when the variable is empty?Of course, in this case, combineifTags andelseBlocks can be implemented. You can write any HTML code inelsea block, even a predefined template snippet.include.

{% if archive.CustomAdHtml %}
    <div class="custom-ad-area">
        {{ archive.CustomAdHtml|safe }}
    </div>
{% else %}
    <div class="default-ad-placeholder">
        <p>广告位招租中...</p>
        <a href="/contact-us">了解详情</a>
    </div>
{% endif %}