How to remove spaces from string in django template

Paul Hansen picture Paul Hansen · Jun 30, 2016 · Viewed 17.3k times · Source

How do you remove all spaces from a string value in a django template?

For example

<a href="www.somesite.com/lookup?id={{ order.id }}"</a>

The order number may have spaces in it and how the templates encodes them breaks the lookup function of the site. (Not our site so can't fix that end)

I'm aware that you can use order.id.strip to get rid of the spaces at the front and end but we need to remove them from the middle of the string as well.

I'm also aware that we could create a custom filter to do it but we like to avoid custom filters for one-off things like this.

Answer

Paul Hansen picture Paul Hansen · Jun 30, 2016

From: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#cut

cut

Removes all values of arg from the given string.

For example:

{{ value|cut:" " }}

If value is "String with spaces", the output will be "Stringwithspaces".

This worked perfectly for what I wanted. Was not easy to find so creating this question to help the google juice for the next person.

So in my example it would be:

<a href="www.somesite.com/lookup?id={{ order.id|cut:" " }}"</a>