18

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?

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

"This specifier uses Python string formatting syntax, with the exception that the leading "%" is dropped"
Note lack of space between stringformat and ".3f" is important! If there is space, then it will crash with "stringformat required 2 arguments, 1 provided" exception!
3

stringformat

Comments

0

I had omit the "%":

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.