【问题标题】:Golang Templates Header with Dynamic Content带有动态内容的 Golang 模板标题
【发布时间】: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


    【解决方案1】:

    os.HostName 添加为template function。在标题中调用该函数。

    下面是解析模板时定义函数的例子:

    t := template.Must(template.New("").Funcs(
        template.FuncMap{"hostname": os.Hostname}).ParseFiles(fnames...))
    

    像这样使用函数:

    {{define "header"}}
        <h1>Device Name is: {{hostname}}</h1>
    {{end}}
    

    Run it on the Playground.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 2022-11-03
      • 2016-12-09
      • 2011-07-27
      相关资源
      最近更新 更多