Jinja gotcha

Posted on January 24, 2024

I had been stuck on a weird issue at work for an hour or so. And got nowhere until I did what thought was total nonsense which turned out to be the solution.

Jinja is pretty common templating engine to use in Python.

To the uninformed, basically you can pass in data to html templates to generate html.

So the template would look something like this:

<html>
...
<ul>
{% for i in my_list%}
<li>{{i}}</li>
{% endfor %}
</ul>
</html>

and python code something like

...

beautiful_list=["roses","are","red"]
self.jinja_env = Environment(loader=FileSystemLoader(settings.template_path))
beautiful_html = template.render(my_list=beautiful_list)

print(beautiful_html)

once you run your python program you would end up with something like this:

<html>
...
<ul>
<li>roses</li>
<li>are</li>
<li>red</li>
</ul>
</html>

If you are familiar with html then it wouldn’t come as a surprise that anything enclosed in <!-- --> is considered as comment. Now look at this piece of html template.

<html>
...
<ul>
{% for i in my_list%}
<!-- {% for d in my_list %} --> 
<li>{{i}}</li>
<!-- {% endfor %} -->
{% endfor %}
</ul>
</html>

Can you spot the issue?

When rendering jinja doesn’t respect the comment line and it was puzzling to me as to why it was printing the same line multiple times. For very long time in my debugging session I refused to entertain the thought that maybe the html comment maybe gets ignored while parsing.

Turns out that was exactly what was happening. The jinja library while parsing didn’t ignore the html commented lines. For some odd reason I thought it would.