From 5ce9d2d2616c2ef7f1958eeb76d3e80e90f41a22 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 ... But if someone wants to merge this, I guess it would be fine. 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 224f5d1ff7d..82cb1345585 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 9571c9233ea..5bc2c05c20f 100644 --- a/tpl/template_funcs.go +++ b/tpl/template_funcs.go @@ -1168,9 +1168,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) @@ -1757,6 +1769,7 @@ func init() { "mul": func(a, b interface{}) (interface{}, error) { return 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 02f5f7ba9ce..863ae198bdc 100644 --- a/tpl/template_funcs_test.go +++ b/tpl/template_funcs_test.go @@ -102,6 +102,7 @@ delimit: {{ delimit (slice "A" "B" "C") ", " " and " }} jsonify: {{ (slice "A" "B" "C") | jsonify }} md5: {{ md5 "Hello world, gophers!" }} sha1: {{ sha1 "Hello world, gophers!" }} +plainify: {{ plainify "Hello world, gophers!" }} ` expected := `chomp:

Blockhead

dateFormat: Wednesday, Jan 21, 2015 @@ -139,6 +140,7 @@ delimit: A, B and C jsonify: ["A","B","C"] md5: b3029f756f98f79e7f1b7f1d1f0dd53b sha1: c8b5b0e33d408246e30f53e32b8f7627a7a649d4 +plainify: Hello world, gophers! ` var b bytes.Buffer