获取Django模板的源代码

2024-06-03 02:06:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个模板的来源。我研究了the template APIs和{a2},但没有成功。在

显然,模板对象keeps no reference指向原始源。在

在搞乱我的代码库之前,我在问:有没有一种简单的方法来获取模板的源代码?在


Tags: the对象方法no代码模板a2源代码
3条回答

有一个很好的捷径叫做render_to_string。在

正如de docs所说:

^{bq}$

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

因此,呈现的变量是一个带有模板源代码的字符串

Template对象不保留对原始源文件的引用,但它们保留对原始源文件的引用,您可以从那里重新读取源文件:

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

若您确切知道加载模板的加载程序是什么,则可以直接使用加载程序方法。在

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

文件名与加载模板时的文件名相同loader.get_模板(文件名)

相关问题 更多 >