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

我试图创建一个处理程序,然后将编译 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”和空白黑页。


我在这里错过了什么?


感谢任何帮助!


冉冉说
浏览 99回答 1
1回答

慕标琳琳

当您在第一个代码中将“vd”传递给 ExecuteTemplate 时,数据传递给主模板,并且当您在“template.html”上调用它时,您必须将数据传递给“body”模板,如下所示:{{&nbsp;template&nbsp;"body"&nbsp;.&nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go