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

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