It's no secret that I love automation, and lately my templating framework of choice has been copier. One hiccup I recently ran into was having spaces in my templated directory names. This makes it harder to run commands against as you need to escape them, and if they end up in a url you end up with ugly %20
all over.
Cookiecutter has the solution
Yes the solution comes from a competing templating framework.
I install copier with pipx, so I need to inject cookiecutter in to my copier environment to use the slugify filter.
pipx inject copier cookiecutter
If you are using a normal virtual environment you can just pip install it.
pip install copier cookiecutter
add the extension to your template
copier.yml
Now to enable the extension you need to declare it in your copier.yml
file in your template.
_jinja_extensions:
- cookiecutter.extensions.SlugifyExtension
Use it | slugify
use-it
Now to use it, anywhere that you want to slugify a variable, you just pipe it into slugify.
❯ tree .
.
├── copier.yml
├── README.md
└── {{ site_name|slugify }}
└── markata.toml.jinja
1 directory, 3 files
Here is a slimmed down version of what the copier.yml
looks like.
site_name:
type: str
help: What is the name of your site, this shows in seo description and the site title.
default: Din Djarin
_jinja_extensions:
- cookiecutter.extensions.SlugifyExtension
Results
Running the template looks a bit like this.
straight from their docs
The next section is straight from the cookiecutter docs
Slugify extension
The cookiecutter.extensions.SlugifyExtension
extension provides a slugify
filter in templates that converts string into its dashed ("slugified") version:
{% "It's a random version" | slugify %}
Would output:
it-s-a-random-version
It is different from a mere replace of spaces since it also treats some special characters differently such as '
in the example above. The function accepts all arguments that can be passed to the slugify
function of
python-slugify
. For example to change the output from
it-s-a-random-version
to it_s_a_random_version
, the separator
parameter
would be passed: `slugify(separator='')`.