Reputation: 17352
My program has a Jinja2 template loaded from a file.
t = env.get_template(filename)
Is it possible to get the template source (I mean the unrendered text, i.e. the contents of the file) from the t
object?
Upvotes: 4
Views: 1278
Reputation: 76406
From the documentation, it does not seem that you can get the source directly. There are two things (at least) which can be done, however.
The filename
property of Template
is
The filename of the template on the file system if it was loaded from there. Otherwise this is None.
So, if were indeed loaded from a file (and it still exists unmodified), you could get the contents by opening and read it.
You could attach it to the Template
object yourself when loading it:
def get_template_with_source(env, filename):
t = env.get_template(filename)
t.source = open(filename).read()
return t
For a nicer version, attaching a proper property dynamically, see this question.
Upvotes: 3