Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 224
Leopd Avatar asked Apr 11 '11 21:04

Leopd


People also ask

How do I use Python code in Django template?

You cannot use python code in django template. This is by design, Django's idea of template is to isolate the presentation logic from the programming code. Save this answer.

What are %s %d in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number.

How do you use %s in Python?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.


1 Answers

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

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

like image 68
Yuval Adam Avatar answered Sep 17 '22 17:09

Yuval Adam