django templates, find string replace with other string

Viewed 61598

Hay, I'm writing some templates but I want to convert " " into "_" within a string.

I want to convert the output of

{{ user.name }}

from something like "My Name" to "My_Name". How do I do this?

4 Answers

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.

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(' ','_')

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 ...

Related