在django模板中使用python字符串格式

Leo*_*opd 13 python django django-templates

有一种简单的方法可以在django模板中使用python字符串格式吗?也就是说,我希望能够在模板中做这样的事情

{{ variable|%.3f }}
Run Code Online (Sandbox Code Playgroud)

我知道在这种情况下,人们可以使用

{{ variable|floatformat:3 }}
Run Code Online (Sandbox Code Playgroud)

但我真的希望能够在django变量上一般使用任何python字符串格式.在我的系统中,必须处理两种不同的格式化输出方式(python vs django)是不方便的,所以我想要标准化.我可以写一个自定义模板标签

{% pyformat variable format="%.3f" %}
Run Code Online (Sandbox Code Playgroud)

或者可能是自定义模板过滤器

{{ variable|pyformat:"%.3f" }}
Run Code Online (Sandbox Code Playgroud)

这些中的任何一个已经存在吗?客户过滤器是否会使用传入的字符串?

Yuv*_*dam 14

{{ variable|stringformat:".3f" }}
Run Code Online (Sandbox Code Playgroud)

资料来源:http://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat

  • "此说明符使用Python字符串格式化语法,但前导"%"被删除除外" (3认同)