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.

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

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.

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

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

Subscribe

Enjoyed this post? Get an email notification when I publish.

comments powered by Disqus