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.
This commit is contained in:
Bjørn Erik Pedersen 2016-03-03 15:53:15 +01:00 committed by Steve Francia
parent e5aa477491
commit e5e1bcc271
3 changed files with 21 additions and 0 deletions

View file

@ -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.

View file

@ -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,

View file

@ -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