i try to loop over a dic in my jinja template. But i always get no output.
dic={"SERVICE1" : "tess","SERVICE2" : "test"}
with open(Path(Path.cwd()/"test.jinja")) as f:
template = Template(f.read()).render(data_nebula_docker)
print(template)
My template looks like this:
{% for item in dic %}
{{item}}
{% endfor %}
Normal Variablse are working fine. Does i have some basic misunderstanding?
Thx for your help!
>Solution :
There are a couple of problems with your code. I’m going to assume the indentation issue in your with
statement is just a copy-and-paste error, and that your code actually looks like:
with open(Path(Path.cwd()/"test.jinja")) as f:
template = Template(f.read()).render(data_nebula_docker)
print(template)
In your template you’re referencing a variable dic
, but you aren’t passing this to the render
method. You want:
from jinja2 import Template
from pathlib import Path
dic = {"SERVICE1": "tess", "SERVICE2": "test"}
with open(Path(Path.cwd() / "test.jinja")) as f:
template = Template(f.read()).render(dic=dic)
print(template)
Which produces:
SERVICE1
SERVICE2
You’ll note that this only prints out the keys in your dictionary. When you iterate over a dictionary (in Jinja or Python), you get a list of keys. If you want (key, value)
tuples instead, use the .items()
method:
{% for item in dic.items() %}
{{item}}
{% endfor %}
Which produces:
('SERVICE1', 'tess')
('SERVICE2', 'test')
Separately, your use of pathlib.Path
is a little convoluted; you can write instead:
with (Path.cwd()/"test.jinja").open() as f:
In the above:
- It’s not necessary to wrap the result of
Path() / "string"
in a call toPath()
(because it’s already aPath
) - A
Path
object has anopen
method, so we can call.open()
on thePath
that results fromPath.cwd()/"test.jinja"
.
Although in this case, your pathlib
based code isn’t much of a win over:
with open("test.jinja") as f: