Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRY method to add a class to <body> in the base template?

This is the general structure of my base.html:

<html>
    <head>
    </head>

    <body class="noscroll">
        <nav class="navbar navbar-static-top navbar-dark bg-inverse">
        </nav>
        {% block content %}
        {% endblock content %}
    </body>
</html>

On certain pages, I want the noscroll class which is essentially overflow-y: hidden; but I also have pages that require the scroll. I could move the navbar into its own snippet and insert that, but such a method seems unsatisfactory. Or I could make a separate base_noscroll.html, but that may lead to inconsistencies, so I would have to nest two templates which again would become unsatisfactory.

like image 379
davidtgq Avatar asked Dec 11 '15 21:12

davidtgq


1 Answers

Just add an override-able block with the default content:

<body class="{% block body_class %}noscroll{% endblock %}">

then the noscroll class is there, or you can override it in a template that extends base.html. Django template blocks can go nearly anywhere; they don't have to wrap entire HTML tags.

If you find yourself overriding this block a lot, you can always just add another template that extends base.html and does the override, then extend that:

# noscroll.html

{% extends 'base.html' %}

{% block body_class %}{# empty to override #}{% endblock %}

Then in subsequent pages you can extend either template. How much flexibility you need is always up to you.

like image 190
Brandon Avatar answered Sep 24 '22 21:09

Brandon