HUGO
Menu
GitHub 87548 stars Mastodon

safe.HTMLAttr

Declares the given key-value pair as a safe HTML attribute.

Syntax

safe.HTMLAttr INPUT

Returns

template.HTMLAttr

Alias

safeHTMLAttr

Introduction

Hugo 使用 Go 的 text/templatehtml/template 包。

text/template 包实现数据驱动的模板以生成文本输出,而 html/template 包实现数据驱动的模板以生成可防止代码注入的安全 HTML 输出。

默认情况下,Hugo 在渲染 HTML 文件时使用 html/template 包。

为了生成可防止代码注入的安全 HTML 输出,html/template 包在某些上下文中转义字符串。

Usage

Use the safe.HTMLAttr function to encapsulate an HTML attribute from a trusted source.

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.

See the Go documentation for details.

Example

Without a safe declaration:

{{ with .Date }}
  {{ $humanDate := time.Format "2 Jan 2006" . }}
  {{ $machineDate := time.Format "2006-01-02T15:04:05-07:00" . }}
  <time datetime="{{ $machineDate }}">{{ $humanDate }}</time>
{{ end }}

Hugo renders the above to:

<time datetime="2024-05-26T07:19:55&#43;02:00">26 May 2024</time>

To declare the key-value pair as safe:

{{ with .Date }}
  {{ $humanDate := time.Format "2 Jan 2006" . }}
  {{ $machineDate := time.Format "2006-01-02T15:04:05-07:00" . }}
  <time {{ printf "datetime=%q" $machineDate | safeHTMLAttr }}>{{ $humanDate }}</time>
{{ end }}

Hugo renders the above to:

<time datetime="2024-05-26T07:19:55+02:00">26 May 2024</time>

Last updated: January 1, 0001
Improve this page