Blog Logo
  • Home
  • About

Concatenating strings in Django templates

by Drew Engelson — 22 Sep 2011

You might think that joining two strings in a Django template would have been simple and straightforward. In modern versions of Django, we can achieve it using the add filter.

{{ "Mary had a little"|add:" lamb." }}

However, in earlier versions of Django [TODO: identify specific version], the add filter only works with numbers. Using it on a string has no effect.

So how to do it?

It looks like we're left with the stringformat filter. This feels quite dirty to me, but it works.

{{ "Mary had a little"|stringformat:"s lamb." }}

Enjoy!

Drew Engelson
Author

Drew Engelson

https://tomatohater.com

I currently lead the Cloud Foundation Services team at Starbucks. We are building the Starbucks PaaS to allow digital platforms to be deployed globally with a focus on automation, scalability, performance, security, and developer experience.

Prior to Starbucks, I led Celerity's Technology Innovation and Architecture practice and founded Zoombit and served in technology leadership at Huge and PBS.

Yes. I seriously hate tomatoes.

All content copyright Tomatohater © 2006-2021 • All rights reserved.
0.06g of CO2/viewWebsite Carbon
 Cleaner than 95% of pages tested