github.com/zhongdalu/gf@v1.0.0/g/net/ghttp/ghttp_response_view.go (about) 1 // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 // 7 8 package ghttp 9 10 import ( 11 "github.com/zhongdalu/gf/g/frame/gins" 12 "github.com/zhongdalu/gf/g/os/gview" 13 ) 14 15 // 展示模板,可以给定模板参数,及临时的自定义模板函数 16 func (r *Response) WriteTpl(tpl string, params ...gview.Params) error { 17 if b, err := r.ParseTpl(tpl, params...); err != nil { 18 r.Write("Template Parsing Error: " + err.Error()) 19 return err 20 } else { 21 r.Write(b) 22 } 23 return nil 24 } 25 26 // 展示模板内容,可以给定模板参数,及临时的自定义模板函数 27 func (r *Response) WriteTplContent(content string, params ...gview.Params) error { 28 if b, err := r.ParseTplContent(content, params...); err != nil { 29 r.Write("Template Parsing Error: " + err.Error()) 30 return err 31 } else { 32 r.Write(b) 33 } 34 return nil 35 } 36 37 // 解析模板文件,并返回模板内容 38 func (r *Response) ParseTpl(tpl string, params ...gview.Params) (string, error) { 39 return gins.View().Parse(tpl, r.buildInVars(params...)) 40 } 41 42 // 解析并返回模板内容 43 func (r *Response) ParseTplContent(content string, params ...gview.Params) (string, error) { 44 return gins.View().ParseContent(content, r.buildInVars(params...)) 45 } 46 47 // 内置变量/对象 48 func (r *Response) buildInVars(params ...map[string]interface{}) map[string]interface{} { 49 vars := map[string]interface{}(nil) 50 if len(params) > 0 { 51 vars = params[0] 52 } else { 53 vars = make(map[string]interface{}) 54 } 55 // 当配置文件不存在时就不赋值该模板变量,不然会报错 56 if c := gins.Config(); c.FilePath() != "" { 57 vars["Config"] = c.GetMap("") 58 } 59 vars["Cookie"] = r.request.Cookie.Map() 60 vars["Session"] = r.request.Session.Map() 61 vars["Get"] = r.request.GetQueryMap() 62 vars["Post"] = r.request.GetPostMap() 63 return vars 64 }