import json import jinja2 # The Jinja2 environment _ENV = None def env_init(force: bool = False): """ Initialize the Jinja2 environment. :type 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. :type 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())