我编写的程序从文件中加载了一个Jinja2模板。
t = env.get_template(filename)
请问是否可以从t
对象中获取模板源代码(即未渲染的文本,即文件的内容)?
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.