从字符串而不是从文件加载模板

Bor*_*ris 34 django-templates

我决定在数据库中保存所有系统电子邮件的模板.这些电子邮件的正文是普通的django模板(带标签).

这意味着我需要模板引擎从字符串而不是从文件加载模板.有没有办法实现这个目标?

Ign*_*ams 34

实例化a django.template.Template(),传递字符串以用作模板.

  • 这不会使用`settings.TEMPLATES ['BACKEND']`中配置的后端,但总是使用Django的模板系统.有没有办法从具有配置后端的字符串创建模板? (3认同)

Qua*_*lis 8

为了补充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不会导致错误。


Tob*_*nst 6

在 >= 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)