Write Cookiecutters faster

Robbert
datamindedbe
Published in
2 min readApr 19, 2023

This one’s about writing cookiecutter templates. 🍪 If you’ve ever done that, you might recognize the following git log:

Commit history of a Cookiecutter template repo

You iterate over the template by 1) modifying the jinja in the template, 2) committing and pushing to git, and 3) executing the cookiecutter to see if it worked. ♻️

All that just to find your rendered project full of whitespace because you forgot to use {%- -%} instead of {% %} in a for loop. 😐
Or to find out it was var.strip(" ") instead of var | strip(" ") .

That’s quite a slow and annoying iteration. 🐢 We can do better.

Ultimately, we’re only interested in “what would this template render to”, given a set of parameters. You can do exactly that in a few lines of python. For example, here I’m debugging some jinja that cleans a user input list. 🧹

from jinja2 import Environment

inputs = {'list_of_keys': 'key1, key with spaces , "key with quotes" '}
template = """
{% for col in list_of_keys.split(",") -%}
"{{ col.strip('\" ') }}"{% if not loop.last %}, {% endif %}
{%- endfor -%}
"""
env = Environment()
print(env.from_string(template).render(inputs))

I save this to a file evaluate_jinja.py and run and modify that instead of pushing to git all the time. My feedback cycle is now reduced to seconds instead of minutes. ⏩

Try it out for yourself!

--

--