add build-in fuction json for package gview

This commit is contained in:
John
2020-11-28 22:48:01 +08:00
parent 55429ad589
commit bfe89e0b12
3 changed files with 21 additions and 0 deletions

View File

@ -137,6 +137,7 @@ func New(path ...string) *View {
"dump": view.buildInFuncDump,
"map": view.buildInFuncMap,
"maps": view.buildInFuncMaps,
"json": view.buildInFuncJson,
})
return view

View File

@ -8,6 +8,7 @@ package gview
import (
"fmt"
"github.com/gogf/gf/internal/json"
"github.com/gogf/gf/util/gutil"
"strings"
@ -215,3 +216,10 @@ func (view *View) buildInFuncToLower(str interface{}) string {
func (view *View) buildInFuncNl2Br(str interface{}) string {
return gstr.Nl2Br(gconv.String(str))
}
// buildInFuncJson implements build-in template function: json ,
// which encodes and returns <value> as JSON string.
func (view *View) buildInFuncJson(value interface{}) (string, error) {
b, err := json.Marshal(value)
return gconv.UnsafeBytesToStr(b), err
}

View File

@ -400,3 +400,15 @@ func Test_BuildInFuncDump(t *testing.T) {
t.Assert(gstr.Contains(r, `"score": 100`), true)
})
}
func Test_BuildInFuncJson(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
v := gview.New()
v.Assign("v", g.Map{
"name": "john",
})
r, err := v.ParseContent("{{json .v}}")
t.Assert(err, nil)
t.Assert(r, `{"name":"john"}`)
})
}