为了账号安全,请及时绑定邮箱和手机立即绑定

使用 2 个 ParseFiles 时,go 模板未接收传递的数据

使用 2 个 ParseFiles 时,go 模板未接收传递的数据

Go
冉冉说 2023-01-03 16:59:19
我试图创建一个处理程序,然后将编译 2 个模板:用于布局目的的 template.html 和实际页面:config.html。此代码构建页面,但未传递任何数据:func config(w http.ResponseWriter, r *http.Request) {    fpTemplate := filepath.Join("static", "template.html")    fpPage := filepath.Join("static", "config.html")    tmpl, err := template.ParseFiles(fpPage, fpTemplate)    if err != nil {        log.Println("webserver.config: " + err.Error())    }    vd := ViewData{&Settings}    err = tmpl.ExecuteTemplate(w, "template.html", vd)    if err != nil {        log.Println("webserver.config: " + err.Error())    }}和 config.html 是这样的:{{define "title"}} Config {{end}}{{define "body"}}<p class="text-break">{{ .}}</p>{{end}},当我运行这段代码时:func config(w http.ResponseWriter, r *http.Request) {    fpTemplate := filepath.Join("static", "template.html")    fpPage := filepath.Join("static", "config.html")    //tmpl, err := template.ParseFiles(fpPage, fpTemplate)    tmpl, err := template.New("config.html").ParseFiles(fpPage, fpTemplate)    if err != nil {        log.Println("webserver.config: " + err.Error())    }    vd := ViewData{&Settings}    err = tmpl.ExecuteTemplate(w, tmpl.Name(), vd)    fmt.Println(err)    //err = tmpl.ExecuteTemplate(w, "template.html", vd)    if err != nil {        log.Println("webserver.config: " + err.Error())    }}我收到错误:模板:没有与模板“config.html”关联的模板“config.html”和空白黑页。我在这里错过了什么?感谢任何帮助!
查看完整描述

1 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

当您在第一个代码中将“vd”传递给 ExecuteTemplate 时,数据传递给主模板,并且当您在“template.html”上调用它时,您必须将数据传递给“body”模板,如下所示:

{{ template "body" . }}


查看完整回答
反对 回复 2023-01-03
  • 1 回答
  • 0 关注
  • 98 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号