duanjue2576 2014-08-14 16:46
浏览 113
已采纳

浏览器无法解释html模板

I have one function in a very small Go application that does a query to a database, retrieves some data and inserts it in the template (main.html). the data is getting inserted into the template (see image), however the html is not being interpreted by the browser (Chrome and Firefox)enter image description here. My browsers are otherwise working fine. Is there something that I'm not doing correct with the template?

func Root(w http.ResponseWriter, r *http.Request) {

    t := template.Must(template.New("main").ParseFiles("main.html"))
    rows, err := db.Query("SELECT title, author, description FROM books")
    PanicIf(err)
    defer rows.Close()

    books := []Book{}

    for rows.Next() {
        b := Book{}
        err := rows.Scan(&b.Title, &b.Author, &b.Description)
        PanicIf(err)
        books = append(books, b)
    }
    t.ExecuteTemplate(w, "main.html", books)

}

main.html

<html>
  <head>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
  </head>


  <body>

    <div class="container">
     <table class="table">
  <tr>
    <th>Title</th>
    <th>Author</th>
    <th>Description</th>
  </tr>
{{ range . }}
  <tr>
    <td>{{.Title}}</td>
    <td>{{.Author}}</td>
    <td>{{.Description}}</td>
  </tr>
{{ end }}
</table>
    </div>
  </body>


</html>
  • 写回答

2条回答 默认 最新

  • doumu5934 2014-08-14 16:49
    关注

    You need to set the content type, although it's rather weird it didn't automatically set it for you.

    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    t.ExecuteTemplate(w, "main.html", books)
    

    //edit

    Also for correctness sake, you should add <!DOCTYPE html> to the top of your template, not related to the problem though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答