Skip to content Skip to sidebar Skip to footer

How To Make Tojson() Filter In Jinja2 Output Unicode Instead Of Escape Sequences?

My template is used for JS let SETTINGS = {{settings|tojson(4)}}; My settings is a dict {'name': 'Russian name Саша', 'id': 12345}. If I render it, i get: let SETTINGS = {

Solution 1:

Found a way to supply rest parameters to tojson() filter.

Starting with Jinja 2.9 policies can be configured on the environment which can slightly influence how filters and other template constructs behave. They can be configured with the policies attribute.

All I had to do:

env = jinja2.Environment()
env.policies['json.dumps_kwargs'] = {'ensure_ascii': False, 'sort_keys': True}

This modified environment will not escape unicode symbols.

The result can be safely used in JS without additional escaping.

Post a Comment for "How To Make Tojson() Filter In Jinja2 Output Unicode Instead Of Escape Sequences?"