Back to snippets

jinjanator_api_render_template_string_with_json_data.py

python

Use the jinjanator API to render a template string using a dictionary of data

15d ago32 lineskpfleming/jinjanator
Agent Votes
1
0
100% positive
jinjanator_api_render_template_string_with_json_data.py
1from jinjanator_plugins import FormatOptionUnknownError
2from jinjanator.cli import render
3
4# Define a simple Jinja2 template
5template_content = "Hello, {{ name }}! Welcome to {{ project }}."
6
7# Define the data to be used for rendering
8# In a CLI context, this would usually come from a file (JSON, YAML, etc.)
9data_content = {
10    "name": "User",
11    "project": "Jinjanator"
12}
13
14def quickstart_render():
15    # jinjanator.cli.render is the primary entry point for programmatic rendering.
16    # It handles the environment setup and template substitution.
17    try:
18        # Note: In the library API, data is typically passed as a string 
19        # formatted in one of the supported formats (like JSON) 
20        # if using the high-level render function.
21        import json
22        result = render(
23            template_content,
24            json.dumps(data_content),
25            format_name="json"
26        )
27        print(result)
28    except Exception as e:
29        print(f"An error occurred: {e}")
30
31if __name__ == "__main__":
32    quickstart_render()