| 1 |
--- |
| 2 |
title: safe.JS |
| 3 |
description: Returns the given string declared as a safe JavaScript expression. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [safeJS] |
| 9 |
returnType: template.JS |
| 10 |
signatures: [safe.JS INPUT] |
| 11 |
aliases: [/functions/safejs] |
| 12 |
--- |
| 13 |
|
| 14 |
## Introduction |
| 15 |
|
| 16 |
{{% include "/_common/functions/go-html-template-package.md" %}} |
| 17 |
|
| 18 |
## Usage |
| 19 |
|
| 20 |
Use the `safe.JS` function to encapsulate a known safe EcmaScript5 Expression. |
| 21 |
|
| 22 |
Template authors are responsible for ensuring that typed expressions do not break the intended precedence and that there is no statement/expression ambiguity as when passing an expression like `{ foo: bar() }\n['foo']()`, which is both a valid Expression and a valid Program with an entirely different meaning. |
| 23 |
|
| 24 |
Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output. |
| 25 |
|
| 26 |
Using the `safe.JS` function to include valid but untrusted JSON is not safe. A safe alternative is to parse the JSON with the [`transform.Unmarshal`][] function and then pass the resultant object into the template, where it will be converted to sanitized JSON when presented in a JavaScript context. |
| 27 |
|
| 28 |
See the [Go documentation][] for details. |
| 29 |
|
| 30 |
## Example |
| 31 |
|
| 32 |
Without a safe declaration: |
| 33 |
|
| 34 |
```go-html-template |
| 35 |
{{ $js := "x + y" }} |
| 36 |
<script>const a = {{ $js }}</script> |
| 37 |
``` |
| 38 |
|
| 39 |
Hugo renders the above to: |
| 40 |
|
| 41 |
```html |
| 42 |
<script>const a = "x + y"</script> |
| 43 |
``` |
| 44 |
|
| 45 |
To declare the string as safe: |
| 46 |
|
| 47 |
```go-html-template |
| 48 |
{{ $js := "x + y" }} |
| 49 |
<script>const a = {{ $js | safeJS }}</script> |
| 50 |
``` |
| 51 |
|
| 52 |
Hugo renders the above to: |
| 53 |
|
| 54 |
```html |
| 55 |
<script>const a = x + y</script> |
| 56 |
``` |
| 57 |
|
| 58 |
[Go documentation]: https://pkg.go.dev/html/template#JS |
| 59 |
[`transform.Unmarshal`]: /functions/transform/unmarshal/ |