如何从Jinja2模板对象中获取模板源代码

4

我编写的程序从文件中加载了一个Jinja2模板。

t = env.get_template(filename)

请问是否可以从t对象中获取模板源代码(即未渲染的文本,即文件的内容)?

1个回答

3
根据文档,似乎不能直接获取源代码。但是至少有两件事情可以做到。
  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.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接