ref: e5e1bcc271246fa96ea8ffdb6a8bbc879cf296ce
parent: e5aa47749157e4c49a645d37df89fa76b0e8f952
author: Bjørn Erik Pedersen <[email protected]>
date: Thu Mar 3 10:53:15 EST 2016
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.
--- a/docs/content/templates/functions.md
+++ b/docs/content/templates/functions.md
@@ -448,6 +448,12 @@
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.
--- a/tpl/template_funcs.go
+++ b/tpl/template_funcs.go
@@ -1169,9 +1169,21 @@
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 @@
"mul": func(a, b interface{}) (interface{}, error) { return helpers.DoArithmetic(a, b, '*') },
"ne": ne,
"partial": partial,
+ "plainify": plainify,
"pluralize": pluralize,
"readDir": readDir,
"ref": ref,
--- a/tpl/template_funcs_test.go
+++ b/tpl/template_funcs_test.go
@@ -108,6 +108,7 @@
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 @@
safeCSS: Bat&Man
safeURL: http://gohugo.io
safeJS: (1*2)
+plainify: Hello world, gophers!
`
var b bytes.Buffer