spaceapi-server/spaceapi_server/template/__init__.py

33 lines
839 B
Python
Raw Normal View History

2019-11-25 02:48:12 +01:00
import json
import jinja2
# The Jinja2 environment
_ENV = None
def env_init(force: bool = False):
2019-11-25 03:14:14 +01:00
"""
2019-11-25 02:48:12 +01:00
Initialize the Jinja2 environment.
2019-11-25 03:14:14 +01:00
:type force: If true, force reload the environment.
"""
2019-11-25 02:48:12 +01:00
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):
2019-11-25 03:14:14 +01:00
"""
2019-11-25 02:48:12 +01:00
Render the given string as a Jinja2 template.
2019-11-25 03:14:14 +01:00
:type template: The template string to render.
"""
2019-11-25 02:48:12 +01:00
# 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())