Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load template from a string instead of from a file

I have 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?

like image 529
Boris Avatar asked Jan 30 '10 08:01

Boris


3 Answers

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

like image 107
Ignacio Vazquez-Abrams Avatar answered Nov 08 '22 15:11

Ignacio Vazquez-Abrams


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.

like image 29
Quant Metropolis Avatar answered Nov 08 '22 14:11

Quant Metropolis


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)
like image 11
Tobias Ernst Avatar answered Nov 08 '22 13:11

Tobias Ernst