我决定在数据库中保存所有系统电子邮件的模板.这些电子邮件的正文是普通的django模板(带标签).
这意味着我需要模板引擎从字符串而不是从文件加载模板.有没有办法实现这个目标?
Ign*_*ams 34
实例化a django.template.Template()
,传递字符串以用作模板.
为了补充Ignacio Vazquez-Abrams 的答案,以下是我用于从字符串获取模板对象的代码段:
from django.template import engines, TemplateSyntaxError
def template_from_string(template_string, using=None):
"""
Convert a string into a template object,
using a given template engine or using the default backends
from settings.TEMPLATES if no engine was specified.
"""
# This function is based on django.template.loader.get_template,
# but uses Engine.from_string instead of Engine.get_template.
chain = []
engine_list = engines.all() if using is None else [engines[using]]
for engine in engine_list:
try:
return engine.from_string(template_string)
except TemplateSyntaxError as e:
chain.append(e)
raise TemplateSyntaxError(template_string, chain=chain)
Run Code Online (Sandbox Code Playgroud)
该engine.from_string
方法将django.template.Template
使用template_string
作为其第一个参数的对象实例化,使用该对象的第一个后端settings.TEMPLATES
不会导致错误。
在 >= Django 3 上使用 django Template 和 Context 对我有用。
from django.template import Template, Context
template = Template('Hello {{name}}.')
context = Context(dict(name='World'))
rendered: str = template.render(context)
Run Code Online (Sandbox Code Playgroud)