I have the following layout.html file which is the main template.
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"/>
</head>
<body class="d-flex vh-100 text-center text-white bg-dark">
<div class="container d-flex w-100 h-100 p-3 mx-auto flex-column">
<header class="mb-auto">
<nav class="navbar navbar-dark bg-dark justify-content-center">
<a class="nav-link active link-light" aria-current="page" href="/">Home</a>
<a class="nav-link link-light" href="/products">Products</a>
<a class="nav-link link-light" href="/contact">Contact</a>
</nav>
</header>
<main class="px-3">
{% block body %}{% endblock %}
</main>
<footer class="mt-auto text-white-50">
<p>Template</p>
</footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
</body>
</html>
The body class uses the bg-dark but for one of the pages I need to use bg-red for the body class. How can I change that? For example I created another page using extends layout.html.
{% extends "layout.html" %}
{% block body %}
<h1>Some text here</h1>
<h2>Some text here also</h2>
{% endblock %}
Should have the new background color in the html file or in .css file? If I put it in the .css file how to indicate the body class just for one specific page? Could be a solution to give an id to the body class and change the color in css file but how to give an id for each separate page? When using the extends layout.html will import the same id for all pages.
CodePudding user response:
1- You can create macro
that allow you to create a custom body, passing style into macro params in order to apply it into inline style.
2 - You can create CSS variable into the layout.html
, then apply it in your style.css > body class
, where the value of the style will be passed from the endpoint return, so for example if the home page will take 'bg-red'
:
- global body background-color
app.py
@application.before_request
def before_request_func():
g.BODY_COLOR = "bg-red"
layout.html
<style>
:root {
--body-color: {{g.BODY_COLOR}};
}
</style>
style.css
body {
font-family: "Montserrat", sans-serif;
background-color: --body-color;
}
- template background color
app.py
@application.route('/')
def index():
b_c = "bg-red"
retun render_template('index.html',b_c=b_c)
layout.html
<style>
:root {
{%if b_c %}
--body-color: {{b_c}};
{%endif%}
}
</style>
style.css
body {
font-family: "Montserrat", sans-serif;
background-color: --body-color;
}