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:
- Jinja2 throws an error if someone tries to render bytes
- 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:
- Jinja2 throws an error if someone tries to render bytes
- Alternatively, Jinja2 automatically converts the bytes to strings using
decode("utf8")
, but I'd prefer the former.
1 Answer
Reset to default 0Although 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 + '' }}