mirror of
https://gitee.com/johng/gf
synced 2026-06-06 16:21:40 +08:00
add build-in fuction json for package gview
This commit is contained in:
@ -137,6 +137,7 @@ func New(path ...string) *View {
|
||||
"dump": view.buildInFuncDump,
|
||||
"map": view.buildInFuncMap,
|
||||
"maps": view.buildInFuncMaps,
|
||||
"json": view.buildInFuncJson,
|
||||
})
|
||||
|
||||
return view
|
||||
|
||||
@ -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
|
||||
}
|
||||
|
||||
@ -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"}`)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user