Golang Web下返回HTML内容处理方法


有两种显示方式,都是一样的,假设我们的方法就叫say,两种调用如下:

{{ say "<div style=\"\">你好</div>" }}
{{"<div style=\"\">你好</div>" |say}}

 

 master是主模板


如果我们要在模板中和页面中都要做这种处理,我们见下面的代码
主模板代码
<!DOCTYPE html>
<html>
<head>
</head>
<body>
     <p>模板上面内容</p> {{block "context" .}}{{end}} <p>模板下面内容</p> {{ say "<div style=\"background-color:red;\">你好</div>" }} </body>
</html>

页面内容

{{template "master" .}} {{define "context"}} {{"<div style=\"background-color:red;\">你好</div>" |say}} {{.}} <p>user内容</p> {{end}}

在模板中和页面中都 显示HTML内容,我们可以通过template.New().Funcs() 设置 一个处理方法

见Main()代码

package main import ( "github.com/gin-gonic/gin"
    "html/template"
    "log" ) // 通过该方法可以将内容以HTML的形式输出,返回类型为template.HTML
func say(s string) template.HTML { return template.HTML(s) } func main(){
engin:=gin.Default() engin.GET(
"/user", func(context *gin.Context) { // 设定funcMap funcMap:=template.FuncMap{"say":say,} // 创建模板并加入设置FuncMap t,err:= template.New("user").Funcs(funcMap).ParseFiles("./view/template/master", "./view/user/user") if err!=nil{ log.Panicln("template.funcs err:",err) } t.ExecuteTemplate(context.Writer,"user","中间内容") }) engin.Run() }

结果

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM