summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorJonas Haag <jonas@lophus.org>2017-10-12 20:59:38 +0200
committerTim Graham <timograham@gmail.com>2018-02-07 18:38:12 -0500
commit8c709d79cbd1a7bb975f58090c17a1178a0efb80 (patch)
tree79e6be4dac2289ca5e4943db9ae071d14f95cdc5 /docs
parentef2512b2ffdb719e5c0fb82142f9ce8478282823 (diff)
Fixed #17419 -- Added json_tag template filter.
Diffstat (limited to 'docs')
-rw-r--r--docs/ref/templates/builtins.txt40
-rw-r--r--docs/releases/2.1.txt3
2 files changed, 42 insertions, 1 deletions
diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt
index 634adf42e3..a4e0a0d455 100644
--- a/docs/ref/templates/builtins.txt
+++ b/docs/ref/templates/builtins.txt
@@ -1782,6 +1782,46 @@ For example::
If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string
``"a // b // c"``.
+.. templatefilter:: json_script
+
+``json_script``
+---------------
+
+.. versionadded:: 2.1
+
+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 a the dictionary ``{'hello': 'world'}``, the output will be:
+
+.. code-block:: html
+
+ <script id="hello-data" type="application/json">{"hello": "world"}</script>
+
+The resulting data can be accessed in JavaScript like this:
+
+.. code-block:: javascript
+
+ var el = document.getElementById('hello-data');
+ var value = JSON.parse(el.textContent || el.innerText);
+
+XSS attacks are mitigated by escaping the characters "<", ">" and "&". For
+example if ``value`` is ``{'hello': 'world</script>&amp;'}``, the output is:
+
+.. code-block:: html
+
+ <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.
+
.. templatefilter:: last
``last``
diff --git a/docs/releases/2.1.txt b/docs/releases/2.1.txt
index 52519170db..ae3dd67bc9 100644
--- a/docs/releases/2.1.txt
+++ b/docs/releases/2.1.txt
@@ -205,7 +205,8 @@ Signals
Templates
~~~~~~~~~
-* ...
+* The new :tfilter:`json_script` filter safely outputs a Python object as JSON,
+ wrapped in a ``<script>`` tag, ready for use with JavaScript.
Tests
~~~~~