Go: template.ParseFiles() doesn't work with {{.active}} but does for {{printf "%s" .active}}

huangapple go评论89阅读模式
英文:

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

&lt;body&gt;
    &lt;h2&gt;Current number of players: {{.active}}&lt;/h2&gt;
&lt;/body&gt;

And my go code looks like

type page struct{
    active string
}
t, _ template.ParseFiles(&quot;page.html&quot;)
t.Execute(w,page{active: &quot;No Players are Online&quot;})

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(&quot;page.html&quot;)
t.Execute(w,page{Active: &quot;No Players are Online&quot;})

and template

&lt;body&gt;
    &lt;h2&gt;Current number of players: {{.Active}}&lt;/h2&gt;
&lt;/body&gt;

Go exports only capitalized struct properties to other modules.

huangapple
  • 本文由 发表于 2015年5月18日 21:19:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/30304320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定