Romaan
Romaan

Reputation: 2757

Django Template: remove underscore and capitalize each word

Is there any filter in Django that can remove underscores and also capitalize each letter of the word OR remove underscores and capitalize the first letter of sentence?

Upvotes: 3

Views: 6817

Answers (2)

Zoie
Zoie

Reputation: 354

@register.filter()
def field_name_to_label(value):
    value = value.replace('_', ' ')
    return value.title()

Upvotes: 6

Gocht
Gocht

Reputation: 10256

To capitalize your word you could use capfirst template tag:

{{ value|capfirst }}
# If value is "django", the output will be "Django".

Here you can find more built-in tags.

To remove underscore, I think there's no filter that do that, you could write your own template tag filter or pre-process the word in your view replacing underscores:

word = 'hello_world'
word = word.replace('_', ' ')

Upvotes: 3

Related Questions