admin管理员组

文章数量:1405624

in a Jinja2 template like "Tell me something: {{s}}", and with s as a bytes value like s = b"foo", the rendered template will look like "Tell me something: b'foo'". How do I avoid this behavior?

Using filters or preprocessing the data does not help in my case, because I'd like to use jinja2 as a building block of something else, and I don't have full control of the input data and of the templates. I am pretty sure this will become an extremely common mistake in my application so I'd like to prevent that.

The desired behavior is that:

  1. Jinja2 throws an error if someone tries to render bytes
  2. Alternatively, Jinja2 automatically converts the bytes to strings using decode("utf8"), but I'd prefer the former.

in a Jinja2 template like "Tell me something: {{s}}", and with s as a bytes value like s = b"foo", the rendered template will look like "Tell me something: b'foo'". How do I avoid this behavior?

Using filters or preprocessing the data does not help in my case, because I'd like to use jinja2 as a building block of something else, and I don't have full control of the input data and of the templates. I am pretty sure this will become an extremely common mistake in my application so I'd like to prevent that.

The desired behavior is that:

  1. Jinja2 throws an error if someone tries to render bytes
  2. Alternatively, Jinja2 automatically converts the bytes to strings using decode("utf8"), but I'd prefer the former.
Share Improve this question asked Mar 24 at 13:36 Alessandro MammanaAlessandro Mammana 11
Add a comment  | 

1 Answer 1

Reset to default 0

Although jinja2 doesn't offer a direct way to test if a variable is a bytes object rather than a string, one easy workaround is to concatenate the variable with an empty string to raise a TypeError: can't concat str to bytes when given a bytes object:

Tell me something: {{ s + '' }}

本文标签: