duanjia7912 2018-02-04 20:02
浏览 39
已采纳

将数据传递到嵌套模板不能按预期方式工作

I was trying to get a struct passed to a nested template in Go, using html/template and tried to achieve it using both template.ParseFiles and template.ParseGlob, but it is not working as per my expectation because my understanding is not clear.

My template code for the file header.html is

{{define "header"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> SiteAdmin - {{.User}}</title>
</head>
{{end}} 

and for the file admin.html is

{{template "header"}}
<body>
"User is {{.User}}"
</body>
</html>

I am using the Execute method on the type *Template as

type Admin struct {
    User string
}


data := new(Admin)
data.User = "Guest"
tpl, err := template.ParseGlob("views/templates/admin/*.html")
CheckForErr(err)
err = tpl.Execute(w, data)
CheckForErr(err)

With the above code, I can pass around the struct data to admin.html, and it shows User is Guest in the browser. But if I try to pass it to any of the nested templates, it wouldn't. The title of the page still shows as SiteAdmin - and not SiteAdmin - Guest. The User data from the struct is visible only if I call it as {{.User}} inside the admin.html file, and any reference to it in the nested templates turns out to be not passed. Is this something achievable?

Thank you all.

  • 写回答

1条回答

  • dtds8802 2018-02-04 20:24
    关注

    You need to use {{ template "header" . }}. As the document in text/template say:

    {{template "name" pipeline}}

    The template with the specified name is executed with dot set to the value of the pipeline.

    In this case, the pipeline you passed into is ., which reffers to the whole data.

    It is somehow unconvenient that documents of html/template is mostly in text/template.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮