获取Django模板的源代码

3 投票
4 回答
3596 浏览
提问于 2025-04-17 21:20

我想获取一个模板的源代码。我查看了模板的API源代码,但没有找到解决办法。

显然,模板对象并没有保存原始源代码的引用。

在我动手修改代码之前,我想问一下:有没有简单的方法可以获取模板的源代码?

4 个回答

-2

模板是一些文本文件(通常是HTML格式,但不一定),当你从某个调用,比如说 django.shortcuts.render,去使用它们时,会根据上下文来渲染这些文件。如果你有一个视图函数,它需要指定使用哪个模板。

根据文档:

from django.shortcuts import render

def my_view(request):
    # View code here...
    return render(request, 'myapp/index.html', {"foo": "bar"},
        content_type="application/xhtml+xml")

在这里,模板的路径是 "templates/myapp/index.html"

0

有一个很棒的快捷方式叫做 render_to_string

根据文档的说法:

它会加载一个模板,渲染它,并返回生成的字符串:

from django.template.loader import render_to_string rendered = render_to_string('my_template.html', {'foo': 'bar'})

所以,变量 rendered 就是一个包含模板源代码的字符串。

2

如果你知道具体是哪个加载器在加载模板,你可以直接使用加载器的方法。

from django.template.loaders.app_directories import Loader
source = Loader.load_template_source(file_name)[0]

file_name 和使用 loader.get_template(file_name) 加载模板时是一样的。

5

Template对象并不会保存对原始源代码的引用,但它们会保存对原始源文件的引用,你可以从那里重新读取源代码:

source = open(template_instance.origin.name, 'r').read()

撰写回答