How to dynamically control the display of content in the template based on conditional logic (if/else)

Calendar 👁️ 68

In AnQiCMS template design, it is possible to flexibly control the display of content based on different conditions, which is the key to realizing the customization and dynamic display of the website.Whether it is to decide whether to display the picture based on whether the article has a thumbnail or to display specific content based on the user's role, conditional logic can provide strong support.AnQiCMS uses a syntax similar to the Django template engine, which makes it very easy for webmaster who are familiar with web development to get started.

Master the basic conditional logic of AnQiCMS templates

The conditional logic of AnQiCMS templates is mainly through{% if ... %}To implement this tag is used to determine whether a conditional expression is true (True), if the condition is true, then executeifLabel the code block inside; if it is false (False), skip. All conditional logic tags must appear in pairs, to{% endif %}end to ensure the integrity of the template structure.

For example, you may want to display a variable only if it exists (such as the title of an article), you can write it like this:

{% if article.Title %}
    <h1>{{ article.Title }}</h1>
{% endif %}

here,article.TitleIs a variable obtained from the backend, if it has a value, the title will be rendered.

Learn advanced usage of conditional logic.

The conditional logic of AnQiCMS templates is not simpleifJudgment, it also supports more complex logic branches and various operators, making content control more refined.

  1. Multi-branch judgment:elseandelifWhen your logic needs to handle scenarios such as 'if...then...else...' or 'if...then...else if...then...else...'elseandelif(the abbreviation of 'else if') comes into play.

    • else:WhenifThe default code block executed when the condition is not met.
    • elifInifafter,elseBefore that, multiple ones can be added.elifTo check other conditions.

    For example, you want to display an image based on whether the article has a thumbnail, and if not, display a prompt text:

    {% if item.Thumb %}
        <img src="{{ item.Thumb }}" alt="{{ item.Title }}" />
    {% else %}
        <p>暂无图片</p>
    {% endif %}
    

    For example, display different welcome messages based on the user ID:

    {% if user.Id == 1 %}
        <p>欢迎管理员!</p>
    {% elif user.Id > 0 %}
        <p>欢迎普通用户!</p>
    {% else %}
        <p>请登录!</p>
    {% endif %}
    
  2. Comparison operatorIn a conditional expression, you can use common comparison operators to compare values:

    • ==(Equal to)
    • !=(Not equal to)
    • >(Greater than)
    • <(Less than)
    • >=(greater than or equal to)
    • <=(less than or equal to)

    These operators can be used to compare numbers, strings, and even boolean values.

  3. Logical operatorTo build more complex conditions, you can use logical operators to combine multiple conditions:

    • andor&&(Logical AND): The entire expression is true only when all conditions are true.
    • oror||(Logical OR): When at least one condition is true, the entire expression is true.
    • notor!(Logical NOT): Reverses the boolean value of the condition.

    For example, display an article only when it has both a title and content:

    {% if article.Title and article.Content %}
        <h1>{{ article.Title }}</h1>
        <p>{{ article.Content }}</p>
    {% endif %}
    

    Or, when a category has subcategories or no documents, display different links:

    {% if item.HasChildren or item.ArchiveCount == 0 %}
        <a href="{{ item.Link }}">{{ item.Title }}(待补充)</a>
    {% else %}
        <a href="{{ item.Link }}">{{ item.Title }}</a>
    {% endif %}
    
  4. inOperator inThe operator can be used to determine whether a value exists in a list, string, or map (map).This is very practical in handling label, multi-select attribute scenarios.You can also combinefilter-containA filter to achieve similar functionality.

    Assuming you have an article'sFlag(for exampleFlag="h"Indicating the headline), want to judge if it is a slide (f) or recommendation (c):

    {% if "f" in item.Flag or "c" in item.Flag %}
        <span class="badge">推荐</span>
    {% endif %}
    

    Or if you have a string containing multiple keywords and you want to check if a word is in it:

    {% set keywords_str = "SEO,网站优化,内容营销" %}
    {% if "SEO" in keywords_str %}
        <p>包含SEO关键词</p>
    {% endif %}
    

Common scenarios in practical applications

After understanding these basic and advanced usage methods, let's see how conditional logic plays a role in practical scenarios in the AnQiCMS template:

  1. Control the activation status of the navigation menuWhen creating a navigation menu, you would usually want the currently visited page to be highlighted in the menu.navListthe tags returned byitemContains in the objectIsCurrentField, it can be easily implemented like this:

    {% navList navs %}
        {% for item in navs %}
            <li class="{% if item.IsCurrent %}active{% endif %}">
                <a href="{{ item.Link }}">{{ item.Title }}</a>
            </li>
        {% endfor %}
    {% endnavList %}
    
  2. Handle the first/last element in the loop.InforIn the loop, you can accessforloopVariable to get the current state of the loop. For example,forloop.CounterYou can get the current loop index (starting from 1), which is very useful for adding a special style to the first element:

    {% archiveList archives with type="list" limit="10" %}
        {% for item in archives %}
            <div class="article-item {% if forloop.Counter == 1 %}featured{% endif %}">
                <!-- 文章内容 -->
            </div>
        {% endfor %}
    {% endarchiveList %}
    
  3. Display dynamically according to the content of the fieldMany times, certain content fields may be empty, and you do not want them to be displayed on the front end.

    • Article descriptionIf:DescriptionEmpty, do not display the wrapped content.div.
      
      {% if item.Description %}
          <div>{{ item.Description }}</div>
      {% endif %}
      
    • Custom field: If you have customized the backend modelauthorField, only whenarchive.authorthe value is present, author information is displayed.
      
      {% archiveDetail archiveAuthor with name="author" %}
      {% if archiveAuthor %}
          <p>作者:{{ archiveAuthor }}</p>
      {% endif %}
      
  4. Show contact information or social media linksBycontactLabel to obtain contact information, you can judge whether the specific social media link exists before displaying the corresponding icon or link, to avoid displaying blank content:

    {% contact contactFacebook with name="Facebook" %}
    {% if contactFacebook %}
        <a href="{{ contactFacebook }}" target="_blank">Facebook</a>
    {% endif %}
    

Optimize template code: Remove extra blank lines

Especially when writing conditional logic, whenifA statement does not contain any renderable content, it is simply used to control the display of other tags, and may cause extra blank lines in the rendered HTML, affecting the page structure or debugging. The AnQiCMS template provides a concise way to remove these lines generated by logical tags such asif/forA blank line is produced, by adding a hyphen within the start or end tag.-.

For example:

{%- if some_condition -%}
    <p>这段内容会在满足条件时显示</p>
{%- endif -%}

In this example, evensome_conditionIt is false, the template engine will not leave the output of the by in HTML.{% if ... %}Any blank line introduced by the tag is very useful for keeping the generated HTML code neat.

Summary

AnQiCMS template conditional logic is a powerful tool for building dynamic and flexible websites. By proficiently usingif/else/elifCombine various comparison and logical operators, you can precisely control the display of each element on the page, thereby greatly enhancing the user experience and

Related articles

How to display copyright information and link to the record number at the bottom of the website?

Clearly display copyright information and filing number at the bottom of your website, which is not only a legal requirement but also a key factor in enhancing the professionalism and user trust of the website.AnQi CMS as an efficient content management system, fully considers these details, allowing you to easily manage and present these important site information. ### Understanding the Importance of Copyright Information and Filing Numbers The copyright statement at the bottom of the website, like a brand watermark, clearly identifies the ownership of the content to visitors, effectively protecting your original achievements.As for websites operating in mainland China

2025-11-08

How to retrieve and display the Logo, thumbnail, and slideshow group on a single page?

In Anqi CMS, single pages (such as "About Us", "Contact Us", etc.) can not only carry rich text information but also greatly enhance the attractiveness and professionalism of the page through visual elements.Retrieve and display the Logo, thumbnail, and slideshow group on a single page, which is a key step to optimize the page display effect.AnQi CMS provides flexible template tags, allowing you to easily achieve these functions.### Understand the composition of visual elements on a single page In Anqi CMS, each single page can have exclusive visual elements to meet different display needs

2025-11-08

How to obtain and display the links and titles of the previous and next articles?

When we manage and publish content in Anqi CMS, in order to enhance the user experience and content discoverability of the website, it is usually necessary to provide the function of navigating to the 'previous article' and 'next article' on the article detail page.This not only encourages readers to continue browsing the content within the site, but also provides a good internal link structure for search engine optimization (SEO).The Anqi CMS provides a very concise and intuitive template tag, allowing us to easily meet this requirement.### Core Functionality: `prevArchive` and `nextArchive`

2025-11-08

How to integrate a category list in the navigation menu and display product documents under each category?

In AnQi CMS, integrating product categories into the navigation menu and displaying the product documents below is a crucial step to enhance website user experience and content organization efficiency.This can help visitors quickly find the information they need, and it also helps search engines better understand the structure of the website. To achieve this goal, we need to make some basic settings in the Anqi CMS backend and integrate the corresponding code in the template files according to these settings.

2025-11-08

How to use for loop to traverse list data in the template and display it?

In website content management, dynamically displaying list data is a very basic and important function.Whether it is a news list, product display, category navigation, or friend links, we need to be able to flexibly obtain data from the backend and present it on the frontend template.AnQiCMS (AnQiCMS) provides a powerful and easy-to-use template engine that allows us to easily meet these requirements, among which the 'for loop' is the core tool for displaying list data.AnQiCMS's template engine adopts a syntax style similar to Django

2025-11-08

How to process and display variable content through filters (such as `truncatechars`, `safe`)?

## Optimize Content Display: Application of Variable Filters in AnQi CMS How to present information accurately and beautifully in website content management is the key to improving user experience.AnQi CMS is a flexible and efficient content management system that provides a powerful template engine, allowing us to refine and display variable content through various filters, thereby better meeting the needs of page layout and information delivery.These filters are like the 'makeup artists' of content, allowing the original data to be displayed in the most appropriate form.The AnQi CMS template engine uses syntax similar to Django

2025-11-08

How to define temporary variables or use macro functions to organize complex display logic in templates?

When using Anqicms to manage website content, we often encounter scenarios where we need to display complex data or reuse similar layouts.If the display logic in the template is not organized effectively, it will soon become long and difficult to read, and it will also be particularly difficult to maintain.Luckyly, Anqi CMS's template engine (which supports Django template engine syntax) provides powerful tools such as defining temporary variables and using macro functions, which can help us elegantly solve these problems, making the template code clear and efficient.Why do we need more flexible template logic

2025-11-08

How does AnQiCMS generate structured data through Json-LD tags to optimize the display results of search engines?

In today's highly competitive online environment, it is more important than ever to make your website content stand out in search engines.Relying solely on keyword stuffing and traditional SEO methods is no longer enough to achieve **results.Structured data, especially structured data implemented through Json-LD format, is becoming a key factor in improving search engine display results and attracting more target users' attention.AnQiCMS (AnQiCMS) knows this and provides powerful and flexible features to help you easily master this technology.### Structured Data

2025-11-08