30

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 4

93

A shorter version of Matthijs' answer:

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

Of course it only works when splitting on whitespace.

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! Just what I needed!
WOW ! how did I miss that ?
my user.name value is 'a.b' How to replace '.' with '_' in django template?
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.

2 Comments

Seems that i cannot use custom filters with a inclusion, any ideas?
For future visitors, see @daniel's answer below, just use {{ user.name.split|join:"_" }} which works only for whitespaces.
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(' ','_')

1 Comment

This works as long as the attribute is not called by a django html page. Recommend setting a self.underscored_name field in the class. +1 anyway because it helped me solve a problem.
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 ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.