Jinja2 Templating

Experimenting with python templating of jinja2 and finding it quite a bit nicer than the razor syntax in ASP.NET for one big reason to me that extracting the engine can be done outside of the application with ease as in the case below I am running the engine by itself to test some templating (doing this in ASP.NET is a pain and sucks my friends)

Code

import json
from jinja2 import Template
from types import SimpleNamespace
import pprint

def sample_data():
    items = {}
    for x in range(10):
        items[x] = {
            "index": x,
            "text": f"Item {x}"
        }
    return items

if __name__ == '__main__':
    current_template = Template("Render {{ text }}")
    results = sample_data()
    for row in results:
        data_row = json.dumps(results[row])
        # print(data_row)
        deserialized = json.loads(data_row, object_hook=lambda d: SimpleNamespace(**d))
        # pprint.pprint(deserialized)
        output = current_template.render(text=getattr(deserialized, 'description', 'nope'))
        print(output)

Output

C:\projects\templates\venv\Scripts\python.exe C:/projects/templates/main.py
Render Item 0
Render Item 1
Render Item 2
Render Item 3
Render Item 4
Render Item 5
Render Item 6
Render Item 7
Render Item 8
Render Item 9

Process finished with exit code 0

Now change the output to reference a non existent field, this line

output = current_template.render(text=getattr(deserialized, 'text', 'nope'))

to

output = current_template.render(text=getattr(deserialized, 'description', 'nope'))

Outputs this

C:\projects\templates\venv\Scripts\python.exe C:/projects/templates/main.py
Render nope
Render nope
Render nope
Render nope
Render nope
Render nope
Render nope
Render nope
Render nope
Render nope

Process finished with exit code 0