admin管理员组

文章数量:1332889

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 = {
    "name": "Russian name \u0421\u0430\u0448\u0430",
    "id": 12345
}

I need to get non-escaped unicode characters. The same way I can do in python using

json.dumps(data, encure_ascii=False)

But tojson() filter accepts only one parameter (indent).

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 = {
    "name": "Russian name \u0421\u0430\u0448\u0430",
    "id": 12345
}

I need to get non-escaped unicode characters. The same way I can do in python using

json.dumps(data, encure_ascii=False)

But tojson() filter accepts only one parameter (indent).

Share Improve this question asked May 1, 2020 at 14:25 Alexander CAlexander C 4,0572 gold badges26 silver badges42 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

There is a way to supply rest parameters to tojson() filter.

Starting with Jinja 2.9 policies can be configured on the environment which influence how filters and other template constructs behave. It can be done by changing some keys of policies attribute.

For your case there is json.dumps_kwargs policy. This is what you have to do:

env = jinja2.Environment()
env.policies['json.dumps_kwargs']['ensure_ascii'] = False

This modified environment will not escape unicode symbols.

本文标签: javascriptHow to make tojson() filter in Jinja2 output Unicode instead of escape sequencesStack Overflow