开发者

Load template from a string instead of from a file

I hav开发者_JAVA技巧e decided to save templates of all system emails in the DB. The body of these emails are normal django templates (with tags).

This means I need the template engine to load the template from a string and not from a file. Is there a way to accomplish this?


Instantiate a django.template.Template(), passing the string to use as a template.


To complement the answer from Ignacio Vazquez-Abrams, here is the code snippet that I use to get a template object from a string:

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)

The engine.from_string method will instantiate a django.template.Template object with template_string as its first argument, using the first backend from settings.TEMPLATES that does not result in an error.


Using django Template together with Context worked for me on >= Django 3.

from django.template import Template, Context

template = Template('Hello {{name}}.')
context = Context(dict(name='World'))
rendered: str = template.render(context)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜