Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple level template inheritance in Jinja2?

I do html/css by trade, and I have been working on and off django projects as a template designer. I'm currently working on a site that uses Jinja2, which I have been using for about 2 weeks. I just found out through reading the documentation that Jinja2 doesn't support multiple level template inheritance, as in you can't do more than one

{% extends "foo" %} 

per rendering. Now I'm pretty sure you can do this in Django, which is powerful because you can specify a base template, specify 3 or 4 templates based on that, and then build the meat of your pages using those base templates. Isn't the point of inheritance so you have more power to abstract so your only really messing with unique code?

In any case I have no idea what to do here. I don't know if there is some way I can do it that will work as well as it could with the Django templates. I'm not exactly an expert at either Django or Jinja(2) but I can provide any information needed.

like image 208
Rey Avatar asked Dec 29 '09 20:12

Rey


People also ask

What is template inheritance?

Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. Sounds complicated but is very basic. It's easiest to understand it by starting with an example.

What is Autoescape in Jinja2?

When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.


2 Answers

One of the best way to achieve multiple level of templating using jinja2 is to use 'include' let say you have 'base_layout.html' as your base template

<!DOCTYPE html> <title>Base Layout</title> <div>   <h1>Base</h1>   .... // write your code here   {% block body %}{% endblock %} </div> 

and then you want to have 'child_layout.html' that extends 'base_layout.

{% include "base_layout.html" %}   <div>   ... // write your code here   </div> {% block body %}{% endblock %} 

and now your page can just extends 'child_layout.html' and it will have both base_layout.html and child_layout.html

{% extends "child_layout.html" %} {% block body %}   ...// write your code here {% endblock %} 
like image 196
Toni Avatar answered Sep 20 '22 13:09

Toni


The way the documentation worded it, it seemed like it didn't support inheritance (n) levels deep.

Unlike Python Jinja does not support multiple inheritance. So you can only have one extends tag called per rendering.

I didn't know it was just a rule saying 1 extends per template.... I now know, with some help from the jinja irc channel.

like image 32
Rey Avatar answered Sep 21 '22 13:09

Rey