Minify JavaScript code containing Jinja2 expressio

2019-08-27 15:53发布

问题:

I pass a JSON-encoded dictionary from Python 3 to Jinja2 template and assign it to a JavaScript variable. My template is as follows

<script>
    var a = {{ json_dict }}; // is rendered as `var a = {"key": "value"};`
</script>

This works as expected, but I'd like to minify JavaScript code containing Jinja2 expressions using Closure Compiler, which currently throws predictable errors like

JSC_PARSE_ERROR: Parse error. '}' expected at line 2 character 9
var a = {{ json_dict }};

What are my options?

回答1:

You wrap it in an eval or equivalent.

a = eval('({{json_dict}})')