html/template

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

<!DOCTYPE> html/template

问题

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

package main

import (
	"html/template"
	"net/http"
)

type Event struct {
    Name string
}

func handler(w http.ResponseWriter, r *http.Request) {
	e := Event{ Name: "Melt! Festival" }
    t, _ := template.ParseFiles("events.html")
    t.Execute(w, e)
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":1337", nil)
}

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

<!DOCTYPE>
<html>
<head>
	<title>Event</title>
</head>
<body>
	<p>
		Event: {{.Name}}
	</p>
</body>
</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.

package main

import (
	&quot;html/template&quot;
	&quot;net/http&quot;
)

type Event struct {
    Name string
}

func handler(w http.ResponseWriter, r *http.Request) {
	e := Event{ Name: &quot;Melt! Festival&quot; }
    t, _ := template.ParseFiles(&quot;events.html&quot;)
    t.Execute(w, e)
}

func main() {
    http.HandleFunc(&quot;/&quot;, handler)
    http.ListenAndServe(&quot;:1337&quot;, nil)
}

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

&lt;!DOCTYPE&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;title&gt;Event&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;p&gt;
		Event: {{.Name}}
	&lt;/p&gt;
&lt;/body&gt;
&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。

使用以下声明:

&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 :

&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:

确定