How do I prevent jinja2 from rendering bytes values with the "b" prefix and single quotes? - Stack Overflow

in a Jinja2 template like "Tell me something: {{s}}", and with s as a bytes value like s = b&

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 + '' }}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744248871a4565069.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信