怎么给模板加一个自己的过滤器?过滤器返回 HTML 为什么容易出 XSS?能读模板变量吗?什么时候注册才合法?这篇把每个坑都跑一遍。
{{ 1234567.891|money }} → ¥1,234,567.89
{{ 1234567.891|money("$", 0) }} → $1,234,568
{{ "hi"|shout }} → HI!
{{ "a b c"|rw }} → c b a
{{ 21|double }} → 42
{{ "x"|bpf }} → bp:x
{{ 3|money(digits=1)|shout }} → ¥3.0!上一篇:Context Processor;下一篇:自定义 Template Global;自动转义详见自动转义与 XSS 防护。
filters 里自定义的与内置的总数: 67 | 内置 54 个
x|bold (x=<script>alert(1)</script>) → <b><script>alert(1)</script></b> x|bold_safe (x=<script>alert(1)</script>) → <b><script>alert(1)</script></b> x|bold_wrong (x=<script>alert(1)</script>) → <b><script>alert(1)</script></b>
{{ "a"|who }}(模板里有 user=ann)→ a@ann
没有 user → a@匿名
{{ "a"|ctx_path }} → a:/path
{{ "a"|envname }} → a|autoescape=select_jinja_autoescapeNone 传给过滤器 → type=NoneType 没定义的变量传给过滤器 → type=Undefined 过滤器里抛异常 → ValueError: 过滤器里出错了 模板里写了不存在的过滤器 → TemplateAssertionError: No filter named 'nope'.
还没处理过请求时 add_template_filter('late') → 成功(test_request_context 与渲染不算「第一个请求」)
第一个请求之后 add_template_filter → AssertionError: The setup method 'add_template_filter' can no longer be called on the application. It has already handled its
直接写 jinja_env.filters["direct"] 之后 → direct:154 个: abs attr batch capitalize center count d default dictsort e escape filesizeformat first float forceescape format groupby indent int items join last length list lower map max min pprint random reject rejectattr replace reverse round safe select selectattr slice sort string striptags sum title tojson trim truncate unique upper urlencode urlize wordcount wordwrap xmlattr