hugo

Unnamed repository; edit this file 'description' to name the repository.

git clone git://git.shimmy1996.com/hugo.git
commit e5e1bcc271246fa96ea8ffdb6a8bbc879cf296ce
parent e5aa47749157e4c49a645d37df89fa76b0e8f952
Author: Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Date:   Thu,  3 Mar 2016 15:53:15 +0100

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.

Diffstat:
Mdocs/content/templates/functions.md | 6++++++
Mtpl/template_funcs.go | 13+++++++++++++
Mtpl/template_funcs_test.go | 2++
3 files changed, 21 insertions(+), 0 deletions(-)
diff --git 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. `{{ "<b>BatMan</b>" | 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
@@ -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
@@ -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 <strong>world</strong>, gophers!" }}
 `
 	expected := `chomp: <p>Blockhead</p>
 dateFormat: Wednesday, Jan 21, 2015
@@ -151,6 +152,7 @@ safeHTML: Bat&Man
 safeCSS: Bat&amp;Man
 safeURL: http://gohugo.io
 safeJS: (1*2)
+plainify: Hello world, gophers!
 `
 
 	var b bytes.Buffer