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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程