dongxie548548 2017-12-04 23:32
浏览 105
已采纳

如何使用Golang模板显示HTML表

I am trying to use html/template package to display a table of information in a web page in Golang. The current implementation of the template I have outputs to standard out.

I want to be able to pass the page content generated by the template to another function that will render my web page.

How to achieve this?

Explanation of code attached below. Basically, I want to capture the result of t.Execute(os.Stdout, persons) where persons is a slice of string. I know that t.Execute only returns an error. But it prints to standard out the template t along with the person name values. I wanted to capture the combined template and person array texts into a variable instead. I would like to assign the content to the body variable in my code below.

    t := template.Must(template.New("").Parse(`<table>{{range .}}<tr><td>{{.}}</td></tr>{{end}}</table>`))

    if err := t.Execute(os.Stdout, persons); err != nil {
       log.Fatal(err)
    }
    title := "User Info Page"
    p := &Page{Title: title, Body: []byte(body)}
    renderTemplate(w, "view", p)
}
  • 写回答

1条回答 默认 最新

  • duanci6484 2017-12-04 23:39
    关注

    Execute the template to a bytes.Buffer. Use the contents of the buffer as the body.

    t := template.Must(template.New("").Parse(`<table>{{range .}}<tr><td>{{.}}</td></tr>{{end}}</table>`))
    
    var body bytes.Buffer
    if err := t.Execute(&body, persons); err != nil {
       log.Fatal(err)
    }
    title := "User Info Page"
    p := &Page{Title: title, Body: body.Bytes()}
    renderTemplate(w, "view", p)
    

    If it's also a requirement to print to stdout, then add the following code after executing the template:

    os.Stdout.Write(body.Bytes())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 为什么安装CSiBridge时出现了这个问题,尝试了很多方法都不行,求详细操作步骤?
  • ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术