| 1 |
--- |
| 2 |
title: safe.CSS |
| 3 |
description: Returns the given string declared as safe CSS. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [safeCSS] |
| 9 |
returnType: template.CSS |
| 10 |
signatures: [safe.CSS INPUT] |
| 11 |
aliases: [/functions/safecss] |
| 12 |
--- |
| 13 |
|
| 14 |
## Introduction |
| 15 |
|
| 16 |
{{% include "/_common/functions/go-html-template-package.md" %}} |
| 17 |
|
| 18 |
## Usage |
| 19 |
|
| 20 |
Use the `safe.CSS` function to encapsulate known safe content that matches any of: |
| 21 |
|
| 22 |
1. The CSS3 stylesheet production, such as `p { color: purple }`. |
| 23 |
1. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`. |
| 24 |
1. CSS3 declaration productions, such as `color: red; margin: 2px`. |
| 25 |
1. The CSS3 value production, such as `rgba(0, 0, 255, 127)`. |
| 26 |
|
| 27 |
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. |
| 28 |
|
| 29 |
See the [Go documentation][] for details. |
| 30 |
|
| 31 |
## Example |
| 32 |
|
| 33 |
Without a safe declaration: |
| 34 |
|
| 35 |
```go-html-template |
| 36 |
{{ $style := "color: red;" }} |
| 37 |
<p style="{{ $style }}">foo</p> |
| 38 |
``` |
| 39 |
|
| 40 |
Hugo renders the above to: |
| 41 |
|
| 42 |
```html |
| 43 |
<p style="ZgotmplZ">foo</p> |
| 44 |
``` |
| 45 |
|
| 46 |
> [!NOTE] |
| 47 |
> `ZgotmplZ` is a special value that indicates that unsafe content reached a CSS or URL context at runtime. |
| 48 |
|
| 49 |
To declare the string as safe: |
| 50 |
|
| 51 |
```go-html-template |
| 52 |
{{ $style := "color: red;" }} |
| 53 |
<p style="{{ $style | safeCSS }}">foo</p> |
| 54 |
``` |
| 55 |
|
| 56 |
Hugo renders the above to: |
| 57 |
|
| 58 |
```html |
| 59 |
<p style="color: red;">foo</p> |
| 60 |
``` |
| 61 |
|
| 62 |
[Go documentation]: https://pkg.go.dev/html/template#CSS |