Solution 1 :

use jinja2 template inheritance

in your base template you need to add block like



<body{% block body_attributes %}{% endblock %}>


and then in child templates you extend base.html template like:


{% extends "base.html" %}
{% block body_attributes %}class="bg-red"{% endblock %}



{% extends "base.html" %}
{% block body_attributes %}class="bg-blue"{% endblock %}


you can add other attributes (id, data-spy="scroll" data-target="#navbar-example3" data-offset="0" if you are using the bootstrap scrollspy … ) for the body tag depending on the page

Solution 2 :

I don’t think you can bind class like that. Here is an example of conditional class binding if its useful in your case.

<div class="{% if black_backgroud %} black {% endif %}">...</div>

and in python

def hello():
    return render_template('hello.html', black_backgroud = True)

Problem :

How do I pass in a variable into a template in Jinja2?
I can normally do it like

<p>Hello, {{ var }}</p>

And then in python do:

def hello():
    return render_template('hello.html', var = "World")

Which will result in:
Hello, World
But, let’s say I want a custom bg-color for every page.

If I try

<body bgcolor="{{ bg_color }}">

and in python do:

def hello():
    return render_template('hello.html', bg_color = "black")

It doesn’t work! Can anyone help?


Comment posted by Jan

Can you please specify

Comment posted by Vthechamp

The color doesn’t change

Comment posted by β.εηοιτ.βε

If you have an html5 doctype (

Comment posted by Vthechamp

I removed the Doctype, but it still not working. I even tried using CSS, but it is still not working


Leave a Reply

Your email address will not be published. Required fields are marked *