Search code examples
djangodjango-templatesdjango-viewswagtailwagtail-snippet

Display based on Django WagtailCMS SITE_ID


How can I create an if block to display one of my sidemenu's based on the WagtailCMS SITE_ID?

Tried this, but it doesn't work

{% if settings.SITE_ID == 1 %}
   {% include 'includes/_home-sidebar-left.html' %}
{% else %}
   {% include 'includes/_home-sidebar.html' %}
{% endif }

Solution

  • Assuming this is a page template, you can access the current site through the page object with page.get_site().

    That being said, you'll end up with magic strings/numbers (for checking the site ID or name) in your templates. One way to get around that would be to use the wagtail.contrib.settings module.

    After setting up the module correctly, create a settings object (which will appear in the admin) in myapp/wagtail_hooks.py:

    from wagtail.contrib.settings.models import BaseSetting, register_setting
    
    
    @register_setting
    class LayoutSettings(BaseSetting):
        POSITION_LEFT = 'left'
        POSITION_RIGHT = 'right'
        POSITIONS = (
            (POSITION_LEFT, 'Left'),
            (POSITION_RIGHT, 'Right'),
        )
        sidebar_position = models.CharField(
            max_length=10,
            choices=POSITIONS,
            default=POSITION_LEFT,
        )
    

    And use the settings in the templates myapp/templates/myapp/mytemplate.html

    {% if settings.myapp.LayoutSettings.sidebar_position == 'left' %}
       {% include 'includes/_home-sidebar-left.html' %}
    {% else %}
       {% include 'includes/_home-sidebar.html' %}
    {% endif }