From 91cb13ce10cb0bd02f186497153eb97a5ec58789 Mon Sep 17 00:00:00 2001 From: Shourai <10200748+Shourai@users.noreply.github.com> Date: Mon, 22 Apr 2024 14:24:52 +0200 Subject: [PATCH] Add TILs about jinja2 --- ...ist-of-dictionaries-as-jinja2-variables.md | 21 +++++++++++++++++++ python/read-jinja2-template-from-file.md | 10 +++++++++ 2 files changed, 31 insertions(+) create mode 100644 python/list-of-dictionaries-as-jinja2-variables.md create mode 100644 python/read-jinja2-template-from-file.md diff --git a/python/list-of-dictionaries-as-jinja2-variables.md b/python/list-of-dictionaries-as-jinja2-variables.md new file mode 100644 index 0000000..8b58693 --- /dev/null +++ b/python/list-of-dictionaries-as-jinja2-variables.md @@ -0,0 +1,21 @@ +# Using a list of dictionaries as variables to render a jinja2 template + +```python +from jinja2 import Environment, FileSystemLoader + +environment = Environment(loader=FileSystemLoader("./")) +template = environment.get_template("template.j2") + +list_of_dicts = [{"a":1, "b":2}, {"a":3, "b":4}] + +print(template.render(variables=list_of_dicts)) +``` + +The important part is the `variables` kwarg. + +```jinja2 +{% for var in variables %} + {{ var.a }} + {{ var.b }} +{% endfor%} +``` diff --git a/python/read-jinja2-template-from-file.md b/python/read-jinja2-template-from-file.md new file mode 100644 index 0000000..273cc72 --- /dev/null +++ b/python/read-jinja2-template-from-file.md @@ -0,0 +1,10 @@ +# How to open an jinja2 template from a file + +```python +from jinja2 import Environment, FileSystemLoader + +environment = Environment(loader=FileSystemLoader("./")) +template = environment.get_template("template.j2") + +print(template.render()) +```