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?
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.
They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number.
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.
{{ variable|stringformat:".3f" }}
Source: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With