From 50cad5e38ca393d4f8c7ef5ca99f7feba5fff003 Mon Sep 17 00:00:00 2001 From: Joe Mooring Date: Fri, 24 Nov 2023 15:51:27 -0800 Subject: [PATCH] tpl/transform: Add transform.XMLEscape template function Fixes #3268 --- content/en/functions/transform/XMLEscape.md | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 content/en/functions/transform/XMLEscape.md diff --git a/content/en/functions/transform/XMLEscape.md b/content/en/functions/transform/XMLEscape.md new file mode 100644 index 000000000..17ed2a13d --- /dev/null +++ b/content/en/functions/transform/XMLEscape.md @@ -0,0 +1,38 @@ +--- +title: transform.XMLEscape +description: Returns the given string, removing disallowed characters then escaping the result to its XML equivalent. +categories: [] +keywords: [] +action: + aliases: [] + related: [] + returnType: string + signatures: [transform.XMLEscape INPUT] +--- + +The `transform.XMLEscape` function removes [disallowed characters] as defined in the XML specification, then escapes the result by replacing the following characters with [HTML entities]: + +- `"` → `"` +- `'` → `'` +- `&` → `&` +- `<` → `<` +- `>` → `>` +- `\t` → ` ` +- `\n` → ` ` +- `\r` → ` ` + +For example: + +```go-html-template +transform.XMLEscape "

abc

" → <p>abc</p> +``` + +When using `transform.XMLEscape` in a template rendered by Go's [html/template] package, declare the string to be safe HTML to avoid double escaping. For example, in an RSS template: + +{{< code file="layouts/_default/rss.xml" >}} +{{ .Summary | transform.XMLEscape | safeHTML }} +{{< /code >}} + +[disallowed characters]: https://www.w3.org/TR/xml/#charsets +[html entities]: https://developer.mozilla.org/en-us/docs/glossary/entity +[html/template]: https://pkg.go.dev/html/template