Jinja2 inheritance outside of Flask

9 views
Skip to first unread message

J Grimmtooth

unread,
Nov 19, 2018, 5:56:38 PM11/19/18
to pocoo-libs
I'm using Jinja2 in situations where I'm either just generating a report to email out (most cases) or in a non-Flask web environment (twisted if it matters).  Some of my templates are getting a little complicated and I'm starting to refactor them out to move blocks of code into separate files. But I'm having problems with inheritance.  I've boiled it down to as simple a test as I can.

Main template, 'index-template.html':

<!DOCTYPE html>
<html lang="en">
<head>
   
<meta charset="UTF-8">
   
<meta http-equiv="refresh" content="420" >
   
<title>jTest</title>
</head>
<body>

{% block testing %}This is a test.{% endblock %}

</body>
</html>




Here is the child template that contains the 'testing' block to replace the parent's block.

{% extends 'index-template.html' %}
{% block testing %}
   
This is not a test.
{% endblock %}




And here is the code that uses it:

from jinja2 import FileSystemLoader, Environment

jLoader
= FileSystemLoader("templates")
jEnv
= Environment(loader=jLoader)
indexTemplate
= jEnv.get_template('index-template.html')

jContent
= indexTemplate.render()

with open("index.html", "w") as fp:
    fp
.write(jContent)



index.html ends up like this:

<!DOCTYPE html>
<html lang="en">
<head>
   
<meta charset="UTF-8">
   
<meta http-equiv="refresh" content="420" >
   
<title>jTest</title>
</head>
<body>

This is a test.

</body>
</html>

Was expecting "this is not a test"

I feel like I'm missing something very fundamental here.  Any pointers?

TIA,

Jeff
Reply all
Reply to author
Forward
0 new messages