| 1 |
--- |
| 2 |
title: safe.HTMLAttr |
| 3 |
description: Declares the given key-value pair as a safe HTML attribute. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [safeHTMLAttr] |
| 9 |
returnType: template.HTMLAttr |
| 10 |
signatures: [safe.HTMLAttr INPUT] |
| 11 |
aliases: [/functions/safehtmlattr] |
| 12 |
--- |
| 13 |
|
| 14 |
## Introduction |
| 15 |
|
| 16 |
{{% include "/_common/functions/go-html-template-package.md" %}} |
| 17 |
|
| 18 |
## Usage |
| 19 |
|
| 20 |
Use the `safe.HTMLAttr` function to encapsulate an HTML attribute from a trusted source. |
| 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 |
{{ with .Date }} |
| 32 |
{{ $humanDate := time.Format "2 Jan 2006" . }} |
| 33 |
{{ $machineDate := time.Format "2006-01-02T15:04:05-07:00" . }} |
| 34 |
<time datetime="{{ $machineDate }}">{{ $humanDate }}</time> |
| 35 |
{{ end }} |
| 36 |
``` |
| 37 |
|
| 38 |
Hugo renders the above to: |
| 39 |
|
| 40 |
```html |
| 41 |
<time datetime="2024-05-26T07:19:55+02:00">26 May 2024</time> |
| 42 |
``` |
| 43 |
|
| 44 |
To declare the key-value pair as safe: |
| 45 |
|
| 46 |
```go-html-template |
| 47 |
{{ with .Date }} |
| 48 |
{{ $humanDate := time.Format "2 Jan 2006" . }} |
| 49 |
{{ $machineDate := time.Format "2006-01-02T15:04:05-07:00" . }} |
| 50 |
<time {{ printf "datetime=%q" $machineDate | safeHTMLAttr }}>{{ $humanDate }}</time> |
| 51 |
{{ end }} |
| 52 |
``` |
| 53 |
|
| 54 |
Hugo renders the above to: |
| 55 |
|
| 56 |
```html |
| 57 |
<time datetime="2024-05-26T07:19:55+02:00">26 May 2024</time> |
| 58 |
``` |
| 59 |
|
| 60 |
[Go documentation]: https://pkg.go.dev/html/template#HTMLAttr |