[Django]-Django templates, find string replace with other string

13👍

There is no built-in tag or filter to do this replacement. Write a filter that splits by a given character, and then combine that with the join filter, or write a filter that does the replacement directly.

93👍

A shorter version of Matthijs’ answer:

{{ user.name.split|join:"_" }}

Of course it only works when splitting on whitespace.

👤daniel

10👍

I like to perform this type of conversions in my view / controller code i.e.:

user.underscored_name = user.name.replace(' ','_')
context['user'] = user

dont be afraid to just add a new (temporary) property and use this in your template:

{{ user.underscored_name }}

If you use this at more places add the method underscored_name to the User model:

class User()
  def underscored_name(self):
    return self.name.replace(' ','_')

4👍

If you dont like to write your own custom tag you could do it like this …

{% for word in user.name.split %}{{word}}{% if not forloop.last %}_{% endif %}{% endfor %}

However its quite verbose …

Leave a comment