spaceapi-server/spaceapi_server/template/__init__.py
2019-11-25 02:48:12 +01:00

32 lines
838 B
Python

import json
import jinja2
# The Jinja2 environment
_ENV = None
def env_init(force: bool = False):
'''
Initialize the Jinja2 environment.
@param force If true, force reload the environment.
'''
global _ENV
if _ENV is None or force:
# Use json.dumps as finalizer in order to preserve complex data structures
_ENV = jinja2.Environment(finalize=json.dumps)
return _ENV
def render(template: str):
'''
Render the given string as a Jinja2 template.
@param template The template string to render
'''
# Make sure the Jinaj2 environment is initialized
env = env_init()
# Create a Jinja2 template from the input string
t = env.from_string(template)
# Render the template and turn the JSON dump back into complex data structures
return json.loads(t.render())