Skip to content

Commit

Permalink
Add plainify template function
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bep committed Mar 12, 2016
1 parent 6fb4e07 commit 5ce9d2d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/content/templates/functions.md
Expand Up @@ -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.

Expand Down
13 changes: 13 additions & 0 deletions tpl/template_funcs.go
Expand Up @@ -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)

Expand Down Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions tpl/template_funcs_test.go
Expand Up @@ -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 <strong>world</strong>, gophers!" }}
`
expected := `chomp: <p>Blockhead</p>
dateFormat: Wednesday, Jan 21, 2015
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 5ce9d2d

Please sign in to comment.