How to judge if there is a thumbnail in the `archiveList` tag in AnQiCMS template through `if` to selectively display images?

Calendar 👁️ 64

In AnQiCMS template development, displaying list content is a common requirement, and how elegantly to handle the images in these lists, especially thumbnails, is directly related to the visual effects and user experience of the website.archiveListTags act as one of the core content calling tags in AnQiCMS, which can help us flexibly obtain various document lists.However, in practice, we often encounter situations where some documents have not set thumbnails, which may lead to broken images or layout chaos on the page.At this time, it is reasonable to use the template inifConditional judgment is particularly important.

UnderstandingarchiveListTags and thumbnail fields

archiveListTags are powerful tools for looping output document lists. When we use it to retrieve a set of documents, for example:

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {# ... 循环内容 ... #}
{% endarchiveList %}

In{% for item in archives %}In such a loop, eachitemrepresents a document object that contains rich field information for display on the front end. There are mainly two key fields related to thumbnails:

  • item.ThumbThumbnail address of the document usually.
  • item.LogoMay represent the main image or large image of the document, and can also be a backup image in some cases.

It is noteworthy that AnQiCMS is very intelligent in handling document images in the background. If we do not manually upload a thumbnail when publishing a document, but the document content contains images, the system will automatically extract the first image in the document content asitem.Thumb. In addition, in the 'Content Settings' we can also configure a 'default thumbnail', when the document does not have an explicit thumbnail, the system will try to use this default image to fill initem.ThumbField. Although there are these automatic processing mechanisms, in some extreme cases (such as, the document content has no images and no default thumbnail is set),item.Thumboritem.Logoit may still be an empty value.

Why is it neededifConditional judgment?

Whenitem.Thumboritem.LogoIf the value is empty, if the template code directly uses it as<img>label'ssrcThe attribute value, the browser cannot load the image, it will usually display a broken image icon. This is not only unattractive, but also affects the professionalism of the website and the trust of users in the content.

UseifThe purpose of conditional judgment is:

  1. Avoid 'broken image':Only when the image address exists and is valid, should it be rendered<img>.
  2. Provide graceful degradation:When there is no thumbnail, we can choose to display a generic placeholder or simply not display the image to keep the page tidy.
  3. Enhanced flexibility:Allow switching between different display logic between with and without images according to different business requirements.

Skillfully useifLabel judgment and display thumbnail.

AnQiCMS template engine supports similar to Django'siflogical judgment tags. We can use{% if condition %} ... {% endif %}such a structure to judgeitem.Thumbwhether the field contains a value.

Example 1: Display the image only when there is a thumbnail

This is the most basic and commonly used judgment method.

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {% for item in archives %}
        <div class="archive-item">
            {% if item.Thumb %}
                <a href="{{ item.Link }}">
                    <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
                </a>
            {% endif %}
            <a href="{{ item.Link }}">
                <h3>{{ item.Title }}</h3>
                <p>{{ item.Description }}</p>
            </a>
        </div>
    {% endfor %}
{% endarchiveList %}

In the above code,{% if item.Thumb %}Will checkitem.ThumbIs there a value? Ifitem.ThumbIt exists (i.e., not empty, not zero, not false), then<img src="{{ item.Thumb }}" ...>This code will be rendered on the page. Otherwise, the image part will be completely ignored, and the page will not appear with a 'broken image'.

Example 2: A placeholder is displayed when there is no thumbnail.

If you want to display a unified placeholder image when there is no document thumbnail, you can combineelsethe statement to achieve this.

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {% for item in archives %}
        <div class="archive-item">
            <a href="{{ item.Link }}">
                {% if item.Thumb %}
                    <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
                {% else %}
                    {# 这里是占位图的地址,可以是一个默认图片,也可以是一个由系统标签获取的全局默认图 #}
                    <img src="/public/static/images/default-thumbnail.jpg" alt="{{ item.Title }} - 无图">
                {% endif %}
            </a>
            <a href="{{ item.Link }}">
                <h3>{{ item.Title }}</h3>
                <p>{{ item.Description }}</p>
            </a>
        </div>
    {% endfor %}
{% endarchiveList %}

Here we introduce a hypothetical placeholder image/public/static/images/default-thumbnail.jpg. Replace with the actual placeholder image address used on the site.

Example 3: Multi-level backup image judgment (priority thumbnail, followed by Logo, then placeholder image)

In some scenarios, you may want a more complex fallback logic, such as prioritizing displayitem.Thumbifitem.ThumbIf not found, try displayingitem.Logoifitem.LogoDoes not exist, finally a universal placeholder is displayed. At this time, you can useelifthe structure.

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {% for item in archives %}
        <div class="archive-item">
            <a href="{{ item.Link }}">
                {% if item.Thumb %}
                    <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
                {% elif item.Logo %}
                    {# 如果 Thumb 为空,检查 Logo 是否存在 #}
                    <img src="{{ item.Logo }}" alt="{{ item.Title }}">
                {% else %}
                    {# Thumb 和 Logo 都为空,显示占位图 #}
                    <img src="/public/static/images/default-placeholder.jpg" alt="{{ item.Title }} - 无图">
                {% endif %}
            </a>
            <a href="{{ item.Link }}">
                <h3>{{ item.Title }}</h3>
                <p>{{ item.Description }}</p>
            </a>
        </div>
    {% endfor %}
{% endarchiveList %}

With such multi-level judgment, it can ensure that the page remains beautiful and consistent regardless of the condition of the document images.

Advanced considerations: combine backend settings

AnQiCMS backend's 'Content Settings' has an option for 'Default Thumbnail'. After configuring this option, the system will generateitem.ThumbIf the document itself does not have a thumbnail and no images can be extracted from the content, it will automatically use this default thumbnail. This means that in many cases,item.ThumbThe field may not be completely empty.

If your website has configured a global default thumbnail and you want the template to fully depend on this backend logic, then the template inif item.ThumbJudgment will be more used to confirm whether it is a "custom" thumbnail, rather than to determine whether any thumbnail exists. In this case, usually only a simple{% if item.Thumb %}It will display becauseitem.ThumbAlmost always there will be a value (custom image or default image). But for **compatibility and fault tolerance, it retainsifJudging is still a good habit, in case the backend logic is adjusted in the future or some special content bypasses the default image settings.

Summary

Used in the AnQiCMS template.archiveListThe label shows the document list throughiflogical judgmentitem.ThumbWhether a field exists is a key technique to ensure page aesthetics and enhance user experience. Whether it is a simple yes or no judgment, or mastering the complex logic of multi-level backup imagesifThe flexible application of labels can help us build more robust and user-friendly website interfaces.


Frequently Asked Questions (FAQ)

Q1: Ifitem.Thumbanditem.LogoIf they are all empty, will the page show a broken image?A1: If you have used in the template{% if item.Thumb %}or{% elif item.Logo %}such conditional judgment, and finally inelseno output in the branch<img>Label, or if output is a valid placeholder, the page will not display the 'broken image' icon. It will render an emptysrcof<img>Label will cause a 'broken image'.

Q2: Besides direct judgmentitem.ThumbAre there more rigorous ways to judge whether the image exists?A2: At the AnQiCMS template level, direct judgmentitem.Thumboritem.LogoWhether there is a value (i.e.{% if item.Thumb %}This is usually strict enough. This is because the AnQiCMS backend tries to ensure that the value is either a valid image path or an empty string when generating these fields.The depth of rigor (such as determining whether the image path can be accessed actually, whether the image file exists, etc.) belongs to the scope of front-end JavaScript error handling or back-end logic, which is beyond the judgment ability of the template tag itself.

Q3: I want to display a fixed placeholder image when there is no thumbnail, how should I operate?A3: You can useif-elsestructure to achieve this goal. In{% if item.Thumb %}ofelseIn the branch, directly output a link to the placeholder image you have set up.<img>And label it. For example:

{% if item.Thumb %}
    <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
{% else %}
    <img src="/path/to/your/placeholder.jpg" alt="默认图片">
{% endif %}

Please replace/path/to/your/placeholder.jpgReplace it with the path to the actual placeholder image.

Related articles

In AnQiCMS template, how to judge if the list is empty and display a prompt of 'No content'?

When using AnQiCMS for website template development, you often encounter situations where you need to display list data, such as article lists, product lists, or image galleries.When we retrieve data through template tags (such as `archiveList` or `categoryList`) and use a `for` loop to iterate over the list, if the list is empty, it is usually necessary to provide the user with a friendly prompt instead of displaying a blank space.How can you elegantly judge whether a list is empty in a `for` loop and display a 'No content' prompt?

2025-11-09

In AnQiCMS template, how to decide whether to display the default image or placeholder based on the existence of a variable?

In the template development of AnQiCMS, we often encounter situations where the content may not contain images.For example, a news article may not have an illustration, or a certain product in a product list may not have uploaded the main image temporarily.In this case, if the template directly calls the image address, it may display a broken image icon or leave an abrupt blank, which undoubtedly affects the overall aesthetics and user experience of the website.To solve this problem, AnQiCMS provides flexible template tags and filters, allowing us to determine whether the image variable exists

2025-11-09

How to elegantly handle null or undefined variables returned by the database in AnQiCMS templates to avoid page errors?

During the development of website templates, we often encounter a headache-inducing problem: when the data obtained from the database is empty (null) or a variable is not defined under certain circumstances, the template rendering will cause an error, resulting in the page not displaying normally and significantly reducing the user experience.AnQiCMS (AnQiCMS) is based on its powerful Go language backend and flexible Django-style template engine, providing us with various elegant solutions for handling such situations, allowing the template to run smoothly even when the data is incomplete.### One, make good use of conditional judgments: `{% if

2025-11-09

What is the difference between the `default_if_none` filter and the `default` filter in the AnQiCMS template, and when should the former be preferred?

In web template development, handling the case where variables may not exist or are empty is a common task.The AnQiCMS template system provides a variety of filters to help us elegantly handle such issues, with `default` and `default_if_none` being two commonly used tools.They both provide a default value when the variable is 'no value', but there is a subtle but important difference in the definition of 'no value'.Understanding these differences can help us control the display of template content more accurately.###

2025-11-09

How to display different content in the AnQiCMS template based on the value of the `item.Status` field (such as approved, in review)?

In website content operation, the review status of the content is a very important link.Whether it is a comment submitted by the user, a forum post, or an article or product information released by the website administrator, it often needs to be reviewed before it can be displayed to the public.AnQiCMS provides a flexible template mechanism that allows us to easily display different content on the front-end page based on the review status of the content (such as "approved" or "in review"), thereby providing users with clearer and more accurate feedback.AnQiCMS template syntax is similar to the Django template engine

2025-11-09

In AnQiCMS template, how to judge and display the 'In stock' or 'Out of stock' status based on the product inventory (`Stock`) quantity?

It is crucial to clearly communicate the inventory status of products to users in website operations, especially for sites involving product display.This not only optimizes the user experience, reduces invalid consultations, but also effectively guides the user's purchase decision.AnQiCMS as a flexible and efficient content management system, implements the display of "in stock" or "out of stock" status according to the product inventory quantity in the template, which is very intuitive. AnQiCMS template system adopts a syntax similar to Django, which allows us to control the display of page content through concise tags and variables.When processing product information

2025-11-09

In AnQiCMS template, how to judge whether a string can be successfully converted to a numeric type and perform conditional processing?

In AnQi CMS template creation, we often encounter situations where we need to process strings entered by users or retrieved from the database.One common requirement is to determine whether a string can be successfully converted to a numeric type and to perform different conditional processing based on the result.This is crucial for data display, calculation, and even simple form validation.The AnQi CMS template engine (based on Go language's Pongo2) provides a rich set of filters (filters) and logical tags, allowing us to flexibly meet this requirement. Below

2025-11-09

What is the default return value when the `integer` and `float` filters fail to convert in the AnQiCMS template?

When building a website on Anqi CMS, we often need to flexibly handle and display data in the template.These, `integer` and `float` filters are very commonly used tools when converting values to integers or floating-point numbers.However, have you ever thought about how the system will handle when these filters receive a value that cannot be recognized as a number?In other words, what default values will these filters return if the conversion operation fails?Understanding this is crucial for us to write robust and predictable template logic.###

2025-11-09