html/template

huangapple go评论128阅读模式
英文:

<!DOCTYPE> html/template

问题

我有一个简单的Go语言Web服务器,它只是将一些数据解析到外部HTML文件中,并将该文件提供给Web服务器。

  1. package main
  2. import (
  3. "html/template"
  4. "net/http"
  5. )
  6. type Event struct {
  7. Name string
  8. }
  9. func handler(w http.ResponseWriter, r *http.Request) {
  10. e := Event{ Name: "Melt! Festival" }
  11. t, _ := template.ParseFiles("events.html")
  12. t.Execute(w, e)
  13. }
  14. func main() {
  15. http.HandleFunc("/", handler)
  16. http.ListenAndServe(":1337", nil)
  17. }

但是,每当我尝试解析带有<!DOCTYPE>的HTML文件时,它会将我的HTML页面解析为文本,而不是在浏览器中呈现HTML。

  1. <!DOCTYPE>
  2. <html>
  3. <head>
  4. <title>Event</title>
  5. </head>
  6. <body>
  7. <p>
  8. Event: {{.Name}}
  9. </p>
  10. </body>
  11. </html>

当我将<!DOCTYPE>从HTML文件中删除时,它可以正常呈现。

有人能告诉我为什么会这样吗?我真的很好奇。我花了两个小时搜索我的Go代码不起作用的原因。

英文:

I've got this simple go lang webserver that does nothing more but parsing some data into an external HTML file and serve that file to the webserver.

  1. package main
  2. import (
  3. &quot;html/template&quot;
  4. &quot;net/http&quot;
  5. )
  6. type Event struct {
  7. Name string
  8. }
  9. func handler(w http.ResponseWriter, r *http.Request) {
  10. e := Event{ Name: &quot;Melt! Festival&quot; }
  11. t, _ := template.ParseFiles(&quot;events.html&quot;)
  12. t.Execute(w, e)
  13. }
  14. func main() {
  15. http.HandleFunc(&quot;/&quot;, handler)
  16. http.ListenAndServe(&quot;:1337&quot;, nil)
  17. }

But whenever I try to parse the HTML file with the <!DOCTYPE> set it parses my html-page as text in stead of rendering the HTML in the browser

  1. &lt;!DOCTYPE&gt;
  2. &lt;html&gt;
  3. &lt;head&gt;
  4. &lt;title&gt;Event&lt;/title&gt;
  5. &lt;/head&gt;
  6. &lt;body&gt;
  7. &lt;p&gt;
  8. Event: {{.Name}}
  9. &lt;/p&gt;
  10. &lt;/body&gt;
  11. &lt;/html&gt;

When I leave the &lt;!DOCTYPE&gt; out of the HTML-file it renders it just fine.

Can anyone tell me why this is because I'm really curious? I spent two hours searching for the cause of my go code not working.

答案1

得分: 2

你的文档类型声明不正确,因此产生了与期望相反的效果:浏览器可能会将其解释为文档不是HTML。

使用以下声明:

  1. &lt;!DOCTYPE html&gt;

参考资料1

英文:

Your doctype declaration is incorrect, thus having an effect opposite from the desired one : it is probably interpreted by the browser as signifying the document isn't HTML.

Use this :

  1. &lt;!DOCTYPE html&gt;

See reference.

答案2

得分: 0

你是否尝试在你的文件中使用DOCTYPE html?

英文:

Have you tried using DOCTYPE html in your file instead?

huangapple
  • 本文由 发表于 2013年7月29日 01:22:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/17910791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定