简体   繁体   中英

Write JS variable containing “</script>” string into Django HTML template

How would I write the following Python object to a JavaScript variable in a template:

{"foo": {"bar": "</script>"}, "baz": 1}

The above object would be written to a JS variable in an HTML template. That variable would then have two properties, foo and baz . The foo property would evaluate to an object having a property bar . A problem is that the </script> tag closes the parent <script> element (in the HTML template) prematurely.

Thanks to spectras.

In Python (2.7):

js = json.dumps({"foo": {"bar": "</script>", "url":"one/two/three"}, "baz": 1})

In the Django (1.7) template:

<script>
var data = JSON.parse('{{ js|escapejs }}');
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM