【发布时间】:2019-02-12 06:19:15
【问题描述】:
我有一个用 Golang 编写的小型网络服务器,可以在一堆 unix 设备上运行。我希望在我的网络服务器提供的每个页面的标题中包含设备的名称,以便我可以知道我正在查看哪个设备。
网络服务器有六个网页,它们都使用嵌套的标题模板。像这样:
<body>
{{template "header"}}
header.html 文件可能是这样的:
{{define "header"}}
<h1>Device Name is: {{.}}</h1>
{{end}}
我希望设备的名称(通过 os.HostName() 获得)位于标题中 - 我不知道如何轻松做到。
我可以做的是在程序开始时获取主机名,然后在每次调用 ExecuteTemplate 时将其传递回 HTML。正如我所说,大约有 6 页,所以有 6 个处理程序,我必须像这样在我的处理程序函数中通过 ExecuteTemplate 将这个名称传回。像这样:
func XYZHandler(w http.ResponseWriter, r *http.Request) {
type returnInfo struct {
Name string
}
XYZReturnInfo := returnInfo{Name: deviceName} // deviceName obtained at start of program
tmpl.ExecuteTemplate(w, "XYZ.html", returnInfo )
}
然后 HTML 页面使用 .Name 将其注入到标题中。
但是有什么方法可以在程序开始时将该 deviceName 值放入标题模板中?那么从那时起它会嵌套到每个页面中吗?
我应该补充一点,我也在启动时解析我的 .html 文件。使用 ParseFiles。
【问题讨论】:
标签: html templates go webserver