dongyingdao8867 2019-02-12 06:19
浏览 103
已采纳

具有动态内容的Golang模板标题

I have a small webserver written in Golang which runs on a bunch of unix devices. I want the name of the device in the header of each page served by my webserver so that I can tell which device I'm looking at.

The webserver has half a dozen web pages, and they all use a nested header template. Like this:

<body>
    {{template "header"}}

And the header.html file could be something like:

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

I want the name of the device (which is obtained through os.HostName()) to be in the header- and I can't figure out how to do it easily.

What I can do is get the host name at the start of the program, and then pass this back to the HTML every time I call ExecuteTemplate. And as I say, there are around 6 pages, so 6 handlers where I'd have to pass this name back via ExecuteTemplate in my handler function like this. Like this:

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 )
}

And then the HTML page injects that into the header using .Name.

But is there some way I can put that deviceName value into the header template once at the start of the program? So that then it gets nested into each page from then on?

I should add I'm parsing my .html files at startup too. Using ParseFiles.

  • 写回答

1条回答 默认 最新

  • douhuiwan5141 2019-02-12 07:13
    关注

    Add os.HostName as a template function. Call that function in the header.

    Here's an example of defining the function when parsing the template:

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

    Use the function like this:

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

    Run it on the Playground.

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

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错