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?
A shorter version of Matthijs' answer:
{{ user.name.split|join:"_" }}
Of course it only works when splitting on whitespace.
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(' ','_')
self.underscored_name field in the class. +1 anyway because it helped me solve a problem.