英文:
Go: template.ParseFiles() doesn't work with {{.active}} but does for {{printf "%s" .active}}
问题
假设我的HTML文件的主体如下所示:
<body>
<h2>当前在线玩家数量:{{.active}}</h2>
</body>
我的Go代码如下所示:
type page struct{
active string
}
t, _ := template.ParseFiles("page.html")
t.Execute(w, page{active: "没有玩家在线"})
当我运行这段代码时,屏幕上什么都没有显示。当我将{{.active}}更改为{{printf "%s" .active}}时,它就可以正常工作了。
我是否总是需要包含printf?我猜我对文档感到困惑。
谢谢!
英文:
Lets say the body of my html file like so
<body>
<h2>Current number of players: {{.active}}</h2>
</body>
And my go code looks like
type page struct{
active string
}
t, _ template.ParseFiles("page.html")
t.Execute(w,page{active: "No Players are Online"})
When I run the code, I get a blank screen. When I change {{.active}} to {{printf "%s" .active}} it works.
Do I always need to include printf? I guess I'm confused by the documentation.
Thanks!
答案1
得分: 1
将active
属性的首字母大写。像这样:
type page struct{
Active string
}
t, _ template.ParseFiles("page.html")
t.Execute(w,page{Active: "No Players are Online"})
和模板
<body>
<h2>当前在线玩家数量:{{.Active}}</h2>
</body>
Go语言只会将首字母大写的结构体属性导出给其他模块。
英文:
Make active
property capitalized. Like so:
type page struct{
Active string
}
t, _ template.ParseFiles("page.html")
t.Execute(w,page{Active: "No Players are Online"})
and template
<body>
<h2>Current number of players: {{.Active}}</h2>
</body>
Go exports only capitalized struct properties to other modules.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论