Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to Python syntax. Then the template is passed data to render the final document.
fromjinja2importEnvironment,FileSystemLoader# loading the environmentenv=Environment(loader=FileSystemLoader('templates'))# loading the templatetemplate=env.get_template('helloName.jinja')# rendering the template and storing the resultant text in variable outputoutput=template.render(name='Geeks')# printing the output on screenprint(output)
message.jinja
Text Only
1234567
Hello {{ name }}!
I'm happy to inform you that you did very well on today's {{ test_name }}.
You reached {{ score }} out of {{ max_score }} points.
See you tomorrow!
Anke
Python
1 2 3 4 5 6 7 8 91011121314151617181920212223
fromjinja2importEnvironment,FileSystemLoadermax_score=100test_name="Python Challenge"students=[{"name":"Sandrine","score":100},{"name":"Gergeley","score":87},{"name":"Frieda","score":92},]environment=Environment(loader=FileSystemLoader("templates/"))template=environment.get_template("message.jinja")forstudentinstudents:filename=f"message_{student['name'].lower()}.txt"content=template.render(student,max_score=max_score,test_name=test_name)withopen(filename,mode="w",encoding="utf-8")asmessage:message.write(content)print(f"... wrote {filename}")