Sep 17, 2018

How to Uppercase the First Letter in Jinja?

I have been using Jinja for my side-project and was surprised to find that there’s no way to uppercase only the first letter. There is a capitalize filter but it also lowercases the rest of the letters—something you wouldn’t want if your text has acronyms or proper nouns. Jinja doesn’t support sentence case by default, but thankfully it’s not hard to recreate that.

Jinja supports Python’s string manipulation syntax, so we can leverage that for our sentence casing.

{% raw  %}<p>Customer's response: {{ response[0]|upper}}{{response[1:] }}</p>{% endraw %}

There you go. Gets the job done. But, you might also prefer not to use a verbose syntax every time. Here, Jinja’s macros come in handy.

{% raw  %}{% macro sentence_case(text) %}
    {{ text[0]|upper}}{{text[1:] }}
{% endmacro %}

<p>{{ sentence_case(comment) }}</p>{% endraw %}

Follow Me!

I write about things that I find interesting. If you're modestly geeky, chances are you'll find them too.

Subscribe to this blog via RSS Feed.

Don't have an RSS reader? Use Blogtrottr to get an email notification when I publish a new post.