Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask jinja2 how to separate header, base and footer?

Tags:

flask

jinja2

I have a question that in my base.html, I have :

<div id="header">{% block header %}{% endblock %}</div>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">{% block footer %}{% endblock %}</div>

For every other page, I always do this:

{% extends "base.html" %}
{% block content %}
...

My question is that I do not want to have my header (or footer) code inside base.html because it's a lot of things, is there anyway that i can have separate files like header.html and footer.html that my "base.html" will get the content from, and every other page which extends "base.html" will also display the content of the header.html and footer.html?

Thank you so much!

like image 254
Kiddo Avatar asked Jul 20 '14 05:07

Kiddo


People also ask

What is Jinja2 flask templates?

Here is some of what jinja2 offers in Flask Templates: You can pass any data from your flask app to the HTML template. Autoescaping ( which is enabled by default). Context processors. Template inheritance. We will explain each one of those in this article. Before you start this tutorial flask should be installed in your virtual environment.

How to pass data from the back-end to the front-end in Jinja2?

Now we are ready to start the tutorial. Jinja2 allows as to pass data form our back-end to the front-end easily, the variables that we pass are called context .Here is an example of passing a variable to the front-end: In the above piece of code we created a flask endpoint that returns a template named index.html when a user visits it.

How do I use Jinja2 template engine?

Jinja2 Template engine. Jinja2 is a template engine for Python. You can use it when rendering data to web pages. For every link you visit, you want to show the data with the formatting. By using a template engine we can seperate display logic (html, css) from the actual Python code. Let’s start with an example.

What are the built-in filters in Jinja2 templates?

There are a bunch of built-in filters that can be used in jinja2 templates, some of the most used filters are title, upper, lower and join ,all of which work as their normal python counterparts str.title () , str.upper () etc. Let's modify the endpoint to pass a list of strings to the front-end using app.py:


1 Answers

Yeah, you can do that using the include statement. So in base.html, wherever you want the content of header.html you put this:

{% include "header.html" %}

http://jinja.pocoo.org/docs/templates/#include

like image 114
Jahaja Avatar answered Sep 22 '22 23:09

Jahaja