20 Star 164 Fork 26

qiqi / orange

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
parse.go 1.94 KB
一键复制 编辑 原始数据 按行查看 历史
qiqi 提交于 2020-12-21 11:36 . 支持直接对模板字符串进行渲染
package view
import (
"bytes"
"gitee.com/zhucheer/orange/utils"
"html/template"
htmlTemplate "html/template"
"net/url"
"path/filepath"
textTemplate "text/template"
)
var htmlTemplateFuncs = template.FuncMap{
"unescaped": unescaped,
"urlencode": urlencode,
"urldecode": urldecode,
}
// TextPath 渲染文本
func TextPath(tplPath string, viewData interface{}, includeFiles ...string) (res string) {
return textPath(tplPath, viewData, includeFiles...)
}
// textPath 渲染文本类型模版
func textPath(tplPath string, viewData interface{}, includeFiles ...string) (res string) {
tplName := filepath.Base(tplPath)
showBuffer := bytes.NewBuffer([]byte{})
tmpl := textTemplate.Must(textTemplate.New(tplName).ParseFiles(tplPath))
tmpl.ParseFiles(includeFiles...)
tmpl.Execute(showBuffer, viewData)
res = showBuffer.String()
return
}
// TextContent 根据模板内容渲染文本类型模版
func TextContent(tplContent string, viewData interface{}, includeFiles ...string) (res string) {
tplName := "ORANGE-TPL" + utils.ShortTag(tplContent, 0)
showBuffer := bytes.NewBuffer([]byte{})
tmpl := textTemplate.Must(textTemplate.New(tplName).Parse(tplContent))
tmpl.ParseFiles(includeFiles...)
tmpl.Execute(showBuffer, viewData)
res = showBuffer.String()
return
}
// htmlPath 渲染html类型模版
func htmlPath(tplPath string, viewData interface{}, includeFiles ...string) (res string) {
tplName := filepath.Base(tplPath)
showBuffer := bytes.NewBuffer([]byte{})
tmpl := htmlTemplate.Must(htmlTemplate.New(tplName).Funcs(htmlTemplateFuncs).ParseFiles(tplPath))
tmpl.ParseFiles(includeFiles...)
tmpl.Execute(showBuffer, viewData)
res = showBuffer.String()
return
}
// unescaped 模版函数
func unescaped(x string) interface{} {
return template.HTML(x)
}
// urlencode
func urlencode(x string) interface{} {
return template.URLQueryEscaper(x)
}
// urldecode
func urldecode(x string) interface{} {
decode, _ := url.PathUnescape(x)
return decode
}
Go
1
https://gitee.com/zhucheer/orange.git
git@gitee.com:zhucheer/orange.git
zhucheer
orange
orange
v0.5.10

搜索帮助