Leopd
Leopd

Reputation: 42727

Using python string formatting in a django template

Is there an easy way to use python string formatting from within a django template? That is, I'd like to be able to do something like this in a template

{{ variable|%.3f }}

I know in this case, one can just use

{{ variable|floatformat:3 }}

But I'd really like to be able to generically use any python string format on a django variable. In my system it's inconvenient to have to deal with two different ways to format output (python vs django), so I'd like to standardize. I could write a custom template tag like

{% pyformat variable format="%.3f" %}

or maybe a custom template filter like

{{ variable|pyformat:"%.3f" }}

Do either of these already exist? Will the customer filter work with a string passed in like that?

Upvotes: 18

Views: 35124

Answers (3)

Yuval Adam
Yuval Adam

Reputation: 165222

{{ variable|stringformat:".3f" }}

Source: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat

Upvotes: 17

hharnisc
hharnisc

Reputation: 927

I had omit the "%":

    {{ variable|stringformat:".3f" }} 

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798556

stringformat

Upvotes: 3

Related Questions