08-02-2023, 04:48 PM
Since Django 2.1 there is the [json-script template tag][1]. From the docs:
> **json_script**
>
> Safely outputs a Python object as JSON, wrapped in a <script> tag,
> ready for use with JavaScript.
>
> Argument: HTML “id” of the <script> tag.
>
> For example:
>
> {{ value|json_script:"hello-data" }}
> If value is the dictionary `{'hello': 'world'}`, the output will be:
>
> <script id="hello-data" type="application/json">
> {"hello": "world"}
> </script>
> The resulting data can be accessed in JavaScript
> like this:
>
> var value = JSON.parse(document.getElementById('hello-data').textContent);
>
> XSS attacks are mitigated by escaping the characters “<”, “>” and “&”. For
> example if value is `{'hello': 'world</script>&amp;'}`, the output is:
>
> <script id="hello-data" type="application/json">
> {"hello": "world\\u003C/script\\u003E\\u0026amp;"}
> </script>
> This is compatible
> with a strict Content Security Policy that prohibits in-page script
> execution. It also maintains a clean separation between passive data
> and executable code.
[1]:
> **json_script**
>
> Safely outputs a Python object as JSON, wrapped in a <script> tag,
> ready for use with JavaScript.
>
> Argument: HTML “id” of the <script> tag.
>
> For example:
>
> {{ value|json_script:"hello-data" }}
> If value is the dictionary `{'hello': 'world'}`, the output will be:
>
> <script id="hello-data" type="application/json">
> {"hello": "world"}
> </script>
> The resulting data can be accessed in JavaScript
> like this:
>
> var value = JSON.parse(document.getElementById('hello-data').textContent);
>
> XSS attacks are mitigated by escaping the characters “<”, “>” and “&”. For
> example if value is `{'hello': 'world</script>&amp;'}`, the output is:
>
> <script id="hello-data" type="application/json">
> {"hello": "world\\u003C/script\\u003E\\u0026amp;"}
> </script>
> This is compatible
> with a strict Content Security Policy that prohibits in-page script
> execution. It also maintains a clean separation between passive data
> and executable code.
[1]:
[To see links please register here]