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.

12/29/2009 8:03:42 PM

Accepted Answer

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.

12/30/2009 1:05:53 AM

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>
  .... // write your code here
  {% block body %}{% endblock %}

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

{% include "base_layout.html" %}
  ... // write your code here
{% 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 %}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow