VPfB
VPfB

Reputation: 17352

How to get the template source from Jinja2 Template object

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

Answers (1)

Ami Tavory
Ami Tavory

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.

  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.

Upvotes: 3

Related Questions