Skip to content

Commit

Permalink
Add jsonify template func
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Mar 6, 2016
1 parent c8c6f5d commit 435e996
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
8 changes: 8 additions & 0 deletions docs/content/templates/functions.md
Expand Up @@ -112,6 +112,14 @@ e.g.
{{ .Render "summary" }}
{{ end }}


### jsonify
Encodes a given object to JSON.

e.g.

{{ dict "title" .Title "content" .Plain | jsonify }}

### last
Slices an array to only the last _N_ elements.

Expand Down
11 changes: 11 additions & 0 deletions tpl/template_funcs.go
Expand Up @@ -16,6 +16,7 @@ package tpl
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"html"
Expand Down Expand Up @@ -1142,6 +1143,15 @@ func markdownify(text string) template.HTML {
return template.HTML(m)
}

// jsonify encodes a given object to JSON.
func jsonify(v interface{}) (template.HTML, error) {
b, err := json.Marshal(v)
if err != nil {
return "", err
}
return template.HTML(b), nil
}

func refPage(page interface{}, ref, methodName string) template.HTML {
value := reflect.ValueOf(page)

Expand Down Expand Up @@ -1522,6 +1532,7 @@ func init() {
"intersect": intersect,
"isSet": isSet,
"isset": isSet,
"jsonify": jsonify,
"last": last,
"le": le,
"lower": func(a string) string { return strings.ToLower(a) },
Expand Down
2 changes: 2 additions & 0 deletions tpl/template_funcs_test.go
Expand Up @@ -98,6 +98,7 @@ in: {{ if in "this string contains a substring" "substring" }}Substring found!{{
seq: {{ seq 3 }}
sort: {{ slice "B" "C" "A" | sort }}
delimit: {{ delimit (slice "A" "B" "C") ", " " and " }}
jsonify: {{ (slice "A" "B" "C") | jsonify }}
`
expected := `chomp: <p>Blockhead</p>
dateFormat: Wednesday, Jan 21, 2015
Expand Down Expand Up @@ -132,6 +133,7 @@ in: Substring found!
seq: [1 2 3]
sort: [A B C]
delimit: A, B and C
jsonify: ["A","B","C"]
`

var b bytes.Buffer
Expand Down

0 comments on commit 435e996

Please sign in to comment.