cusejuice
cusejuice

Reputation: 10681

Django Get First Letter of String

How can I get the first letter of a string in a template with Django? I tried using the truncatechars filter, but it adds an ellipsis at the end.

{{ stringvariable | truncatechars:1 }}  

I would like to go from "John" to "J".

Upvotes: 6

Views: 4843

Answers (1)

alecxe
alecxe

Reputation: 473823

You can use built-in slice template filter:

{{ stringvariable|slice:"1" }}

Demo:

>>> from django.template import Template, Context
>>> t = Template('{{ stringvariable|slice:"1" }}')
>>> c = Context({'stringvariable': 'John'})
>>> t.render(c)
u'J'

Upvotes: 10

Related Questions