How `if` logical judgment tags and `for` loop iteration tags control the conditional display and repeated display of content?

In the daily operation of AnQi CMS, we often need to decide according to different business logic which content should be displayed, and how to efficiently repeat the display of a large number of similar contents. At this time,ifLogical judgment tags andforThe loop to traverse tags becomes an indispensable tool in template design.They allow us to flexibly control the conditional display and repetition of content, greatly enhancing the dynamism and maintainability of the website.

Conditional display tool -iflogical judgment tag

ifTags are the basis for conditional display of content in Anqi CMS templates.It allows us to set one or more conditions, and the corresponding template content will be rendered only when these conditions are met.This is very useful in many scenarios, such as displaying specific information based on the user's permissions, or determining whether to display certain data based on its existence.

The basic usage is to determine whether a variable exists or is true.For example, on the article detail page, we may want to display the image only when the article is set with a thumbnail, otherwise it should not be displayed to avoid broken image placeholders.This is how it can be written:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}" class="article-thumb">
{% endif %}

here,archive.ThumbRepresents the thumbnail path of the article. If this path exists (not empty), thenifThe condition is met, and the image will be displayed.

When the logical judgment needs to be more complex,ifTags also supportelif(short for else if) andelseto handle multiple branching conditions. For example, we want to display different badges based on the recommendation attributes of the article(Flag):

{% if archive.Flag == "h" %}
    <span class="flag-hot">头条</span>
{% elif archive.Flag == "c" %}
    <span class="flag-recommend">推荐</span>
{% else %}
    <span class="flag-normal">普通</span>
{% endif %}

Through such a structure, we can easily deal with various combinations of conditions, ensuring that the content is presented according to precise business rules. At the same time,ifthe label also supports various comparison operators (such as==/!=/</>/>=/<=)and logical operators(and/or/not)even can pass throughinto determine whether a value is included in a set, making conditional judgment more powerful and flexible.

Master of repetitive content layout——forLoop through tags

On the website, article lists, product displays, navigation menus, image galleries, and other content often have repetitive structures.forThe loop iteration tag is born to solve such problems, it allows us to efficiently traverse a data collection (such as an array, slice, or map), and render the same template structure for each element of the collection, but fill in different data.

A common scenario is to display the latest article list. ByarchiveListtags to get the collection of articles, we can thenforuse a loop to sequentially display the title and link of each article:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <li class="article-item">
            <a href="{{ item.Link }}">{{ item.Title }}</a>
            <p>{{ item.Description|truncatechars:100 }}</p>
        </li>
    {% endfor %}
{% endarchiveList %}

here,archivesIsarchiveListThe tag returns a collection of article list data,itemwhich represents the current article object in the loop. Each loop,itemWill automatically update to the next article data in the list until all articles are processed.

Furthermore,forThe loop also provides some useful auxiliary variables and functions. For example,forloop.CounterYou can get the current loop index (starting from 1),forloop.RevcounterThis indicates the remaining number of loop iterations. These are very useful when you need to add special styles to the first or last element of a list:

{% for item in archives %}
    <li class="article-item {% if forloop.Counter == 1 %}first-item{% endif %}">
        <!-- 内容 -->
    </li>
{% endfor %}

Furthermore,forTags also supportreversedto traverse the set in reverse order,sortedSort the set of numbers as wellcycleTag to alternate the predefined string sequence in a loop (for example, to alternate the setting of list items)oddandevenClass name), these can make our template design more exquisite.

If you encounter an empty data set,forthe loop also providesemptyblocks to elegantly handle. Whenarchivesthe list is empty,emptyThe content within the block will be rendered, preventing the page from appearing blank or with errors:

{% for item in archives %}
    <!-- 文章列表内容 -->
{% empty %}
    <p class="no-content">当前暂无文章。</p>
{% endfor %}

Optimize the experience: Details in control and skills

In practical applications,ifandforLabels are often used together to achieve finer content control. For example, when displaying a list of categories in a loop, we may want only items with subcategories to expand and display their subcategories:

{% navList navList %}
    {% for item in navList %}
        <li>
            <a href="{{ item.Link }}">{{ item.Title }}</a>
            {% if item.NavList %} {# 判断是否有下级导航 #}
                <ul class="sub-menu">
                    {% for subItem in item.NavList %}
                        <li><a href="{{ subItem.Link }}">{{ subItem.Title }}</a></li>
                    {% endfor %}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
{% endnavList %}

Here, outer layerforLoop through the main navigation items, inner layerifConditionally judge whether each main navigation item hasNavList(sub-navigation list). If there is, then go through another inner layer}forLoop through and display sub-navigation items.

Another practical trick is to use the template tag's blank line removal feature. Iniforforadd before and after the tag.-The symbol, can remove the blank line occupied by the tag, which is very useful for generating compact HTML code, especially when dealing with list items or inline elements:

{%- for item in archives %}
    {{- item.Id }}
{%- endfor %}

This ensures that the generated HTML does not contain any unnecessary blank lines, making the code cleaner.

By mastering the use ofifandforThese two core tags, combined with the rich data tags provided by Anqi CMS, allow us to flexibly build various complex and dynamic website content layouts like building blocks.This not only improves the development efficiency, but also provides great convenience for the long-term operation and content update of the website.


Frequently Asked Questions (FAQ)

  1. Question:ifTags can be used to determine what types of data?Answer:ifTags are very flexible, can judge boolean values (trueorfalse), numeric size, whether the string content matches, whether the variable exists (non-empty), and even throughinThe operator determines whether a value is contained within an array or a map. This makes it capable of covering the vast majority of conditional judgment needs.

  2. Question: How toforApply different styles to list items in a loop, such as alternating colors?Answer: You canforUsing a loopcycletags. For example, `{% cycle "odd" "even"}