Skip to content

Commit 4bb7351

Browse files
committed
docs: Document the need to use json_encode in javascript contexts
This has always been necessary but we didn't have any explicit guidance for using javascript in templates before.
1 parent c0d5b68 commit 4bb7351

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

docs/guide/templates.rst

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,25 @@ Consequently, if you write random stuff inside of your template
118118
expressions, you will get random Python errors when you execute the
119119
template.
120120

121-
All template output is escaped by default, using the
122-
`tornado.escape.xhtml_escape` function. This behavior can be changed
121+
Security
122+
~~~~~~~~
123+
124+
Inserting untrusted content into a web page can lead to security vulnerabilities such as cross-site
125+
scripting (XSS). All data that is passed to a template should be *escaped* to prevent these
126+
vulnerabilities. The correct form of escaping is context-dependent; Tornado's templates are not
127+
aware of the syntax of HTML, JavaScript, etc, and so the template developer must sometimes
128+
explicitly apply the correct escaping function.
129+
130+
The default escaping function is `tornado.escape.xhtml_escape`, which is appropriate for HTML body
131+
content (but not attribute values). In other cases, other functions should be used. In JavaScript,
132+
use the `.json_encode` function, e.g. ``<script>var x = {{ json_encode(some_object) }};</script>``.
133+
`.json_encode` can be used to escape strings, numbers, lists, and dicts. In this example, the
134+
JavaScript variable ``x`` will be the corresponding JavaScript type (string, number, array, or
135+
object), and not the JSON-encoded string representation. Note that it is unsafe to use
136+
`.json_encode` in the context of a JavaScript string literal (including template strings), only in
137+
the top-level syntactic context.
138+
139+
The automatic escaping behavior can be disabled
123140
globally by passing ``autoescape=None`` to the `.Application` or
124141
`.tornado.template.Loader` constructors, for a template file with the
125142
``{% autoescape None %}`` directive, or for a single expression by

0 commit comments

Comments
 (0)