From e5e1bcc271246fa96ea8ffdb6a8bbc879cf296ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Thu, 3 Mar 2016 15:53:15 +0100 Subject: [PATCH] Add plainify template function To strip away any HTML. May be useful for the .Title in head etc. People may shoot themself in the foot with this, maybe ... The replacement function is pretty fast. --- docs/content/templates/functions.md | 6 ++++++ tpl/template_funcs.go | 13 +++++++++++++ tpl/template_funcs_test.go | 2 ++ 3 files changed, 21 insertions(+) diff --git a/docs/content/templates/functions.md b/docs/content/templates/functions.md index 984efc9b1..ef576bb60 100644 --- a/docs/content/templates/functions.md +++ b/docs/content/templates/functions.md @@ -448,6 +448,12 @@ Runs the string through the Markdown processor. The result will be declared as " e.g. `{{ .Title | markdownify }}` +### plainify + +Strips any HTML and returns the plain text version. + +e.g. `{{ "BatMan" | plainify }}` → "BatMan" + ### pluralize Pluralize the given word with a set of common English pluralization rules. diff --git a/tpl/template_funcs.go b/tpl/template_funcs.go index 29bb6dd04..5fb496c14 100644 --- a/tpl/template_funcs.go +++ b/tpl/template_funcs.go @@ -1169,9 +1169,21 @@ func emojify(in interface{}) (template.HTML, error) { if err != nil { return "", err } + return template.HTML(helpers.Emojify([]byte(str))), nil } +// plainify strips any HTML and returns the plain text version. +func plainify(in interface{}) (string, error) { + s, err := cast.ToStringE(in) + + if err != nil { + return "", err + } + + return helpers.StripHTML(s), nil +} + func refPage(page interface{}, ref, methodName string) template.HTML { value := reflect.ValueOf(page) @@ -1674,6 +1686,7 @@ func init() { "mul": func(a, b interface{}) (interface{}, error) { return helpers.DoArithmetic(a, b, '*') }, "ne": ne, "partial": partial, + "plainify": plainify, "pluralize": pluralize, "readDir": readDir, "ref": ref, diff --git a/tpl/template_funcs_test.go b/tpl/template_funcs_test.go index 983a97d2a..77cd52a33 100644 --- a/tpl/template_funcs_test.go +++ b/tpl/template_funcs_test.go @@ -108,6 +108,7 @@ safeHTML: {{ "Bat&Man" | safeHTML | safeHTML }} safeCSS: {{ "Bat&Man" | safeCSS | safeCSS }} safeURL: {{ "http://gohugo.io" | safeURL | safeURL }} safeJS: {{ "(1*2)" | safeJS | safeJS }} +plainify: {{ plainify "Hello world, gophers!" }} ` expected := `chomp:

Blockhead

dateFormat: Wednesday, Jan 21, 2015 @@ -151,6 +152,7 @@ safeHTML: Bat&Man safeCSS: Bat&Man safeURL: http://gohugo.io safeJS: (1*2) +plainify: Hello world, gophers! ` var b bytes.Buffer