Debian Codegraph @

docs/content/en/functions/safe/JSStr.md

raw
1 ---
2 title: safe.JSStr
3 description: Declares the given string as a safe JavaScript string.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: [safeJSStr]
9 returnType: template.JSStr
10 signatures: [safe.JSStr INPUT]
11 aliases: [/functions/safejsstr]
12 ---
13
14 ## Introduction
15
16 {{% include "/_common/functions/go-html-template-package.md" %}}
17
18 ## Usage
19
20 Use the `safe.JSStr` function to encapsulate a sequence of characters meant to be embedded between quotes in a JavaScript expression.
21
22 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.
23
24 See the [Go documentation][] for details.
25
26 ## Example
27
28 Without a safe declaration:
29
30 ```go-html-template
31 {{ $title := "Lilo & Stitch" }}
32 <script>
33 const a = "Title: " + {{ $title }};
34 </script>
35 ```
36
37 Hugo renders the above to:
38
39 ```html
40 <script>
41 const a = "Title: " + "Lilo \u0026 Stitch";
42 </script>
43 ```
44
45 To declare the string as safe:
46
47 ```go-html-template
48 {{ $title := "Lilo & Stitch" }}
49 <script>
50 const a = "Title: " + {{ $title | safeJSStr }};
51 </script>
52 ```
53
54 Hugo renders the above to:
55
56 ```html
57 <script>
58 const a = "Title: " + "Lilo & Stitch";
59 </script>
60 ```
61
62 [Go documentation]: https://pkg.go.dev/html/template#JSStr