safe.JS
Syntax
Returns
Alias
Introduction
Hugo 使用 Go 的 text/template 和 html/template 包。
text/template 包實現數據驅動的模板以生成文本輸出,而 html/template 包實現數據驅動的模板以生成可防止代碼注入的安全 HTML 輸出。
默認情況下,Hugo 在渲染 HTML 文件時使用 html/template 包。
為了生成可防止代碼注入的安全 HTML 輸出,html/template 包在某些上下文中轉義字符串。
Usage
Use the safe.JS function to encapsulate a known safe EcmaScript5 Expression.
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 a very different meaning.
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.
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.
See the Go documentation for details.
Example
Without a safe declaration:
{{ $js := "x + y" }}
<script>const a = {{ $js }}</script>Hugo renders the above to:
<script>const a = "x + y"</script>To declare the string as safe:
{{ $js := "x + y" }}
<script>const a = {{ $js | safeJS }}</script>Hugo renders the above to:
<script>const a = x + y</script>