Load a Jinja2 template from the filesystem and render it

import os
import jinja2


def render(tpl_path, context):
    path, filename = os.path.split(tpl_path)
    return jinja2.Environment(
        loader=jinja2.FileSystemLoader(path or './')
    ).get_template(filename).render(context)

Usage:

Assuming a template at /some/path/my_tpl.html, containing:

    Hello {{ firstname }} {{ lastname }}!
context = {
    'firstname': 'John',
    'lastname': 'Doe'
}
result = render('/some/path/my_tpl.html', context)

print(result)
Hello John Doe!

About this Entry

Related Content


Comments