Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove spaces from string in django template

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.

like image 284
Paul Hansen Avatar asked Jun 30 '16 01:06

Paul Hansen


1 Answers

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>
like image 167
Paul Hansen Avatar answered Oct 04 '22 05:10

Paul Hansen