Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the template source from Jinja2 Template object

Tags:

python

jinja2

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?

like image 292
VPfB Avatar asked Oct 24 '25 02:10

VPfB


1 Answers

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.

  1. 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.

  2. 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.

like image 152
Ami Tavory Avatar answered Oct 25 '25 17:10

Ami Tavory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!