Home > Software engineering >  Django (Wagtail) template not recognizing page type for if condition
Django (Wagtail) template not recognizing page type for if condition

Time:05-06

On my wagtail blog, I have a simple model that will be the index page listing different articles, defined in my models.py as:

class ArticleIndex(Page):
    description = models.CharField(max_length=255, blank=True,)

    content_panels = Page.content_panels   [FieldPanel("description", classname="full")]

I have some template tags setup to show categories and tags in the sidebar, which should only activate on the index page, not actual article pages. I have this setup thusly:

  {% if article_index %}

  {% categories_list %}

  {% tags_list %}

  {% endif %}

If I remove the if condition, everything displays as I want, so I know it is not an issue with the template tags.

I don't understand why {% if article_index %} is failing, as that's what the page type is.

How can I print out what the actual page type is to see where the discrepancy is, or to see why the if condition is failing?

CodePudding user response:

{% if article_index %} means "if the variable article_index is defined and has a true value". Since you haven't defined a variable named article_index - and there's nothing in Wagtail that makes a variable of that name appear just because the page type is ArticleIndex - it will always be false.

On the other hand, the variable page is always available, so an alternative way of achieving this would be:

{% if page.content_type.model == 'articleindex' %}

However, since each page type has its own dedicated template, it usually isn't necessary to do this kind of check based on page type. The normal way to have different things showing in the sidebar is to use template inheritance - for example, if your base.html template is:

<html>
    <head>...</head>
    <body>
        <div id="sidebar">
            {% block sidebar %}
            {% endblock %}
        </div>
        <div id="content">
            {% block content %}
            {% endblock %}
        </div>
    </body>
</html>

then you can set the content of the sidebar just for the article index page by defining {% block sidebar %} in article_index.html:

{% extends "base.html" %}

{% block sidebar %}
    {% categories_list %}
    {% tags_list %}
{% endblock %}

{% block content %}
    main page content goes here
{% endblock %}
  • Related