From: Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Date: Sun, 6 Mar 2016 13:58:15 +0000 (+0100)
Subject: Add jsonify template func
X-Git-Tag: v0.16~284
X-Git-Url: http://git.maquefel.me/?a=commitdiff_plain;h=435e996c4fd48e9009ffa9f83a19fb55f0777dbd;p=brevno-suite%2Fhugo

Add jsonify template func
---

diff --git a/docs/content/templates/functions.md b/docs/content/templates/functions.md
index 146ab8e9..979e603f 100644
--- a/docs/content/templates/functions.md
+++ b/docs/content/templates/functions.md
@@ -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.
 
diff --git a/tpl/template_funcs.go b/tpl/template_funcs.go
index 4d88336d..d42d9e5e 100644
--- a/tpl/template_funcs.go
+++ b/tpl/template_funcs.go
@@ -16,6 +16,7 @@ package tpl
 import (
 	"bytes"
 	"encoding/base64"
+	"encoding/json"
 	"errors"
 	"fmt"
 	"html"
@@ -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)
 
@@ -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) },
diff --git a/tpl/template_funcs_test.go b/tpl/template_funcs_test.go
index 602fbc5d..02d31fe9 100644
--- a/tpl/template_funcs_test.go
+++ b/tpl/template_funcs_test.go
@@ -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
@@ -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