英文:
html template returns text instead of html
问题
我有以下代码:
package main
import (
"fmt"
htmlTempl "html/template"
"log"
"net/http"
)
var templatesHtml *htmlTempl.Template
var err error
func init() {
fmt.Println("Starting up.")
templatesHtml = htmlTempl.Must(htmlTempl.ParseGlob("templates/*.html"))
}
func test(w http.ResponseWriter, r *http.Request) {
err = templatesHtml.ExecuteTemplate(w, "other.html", nil)
if err != nil {
log.Fatalln(err)
}
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
http.HandleFunc("/test", test)
server.ListenAndServe()
}
我的模板是:
// base.html的内容:
{{define "base"}}
<html>
<head>{{template "head" .}}</head>
<body>{{template "body" .}}</body>
</html>
{{end}}
和
// other.html的内容:
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}
我在http://127.0.0.1:8080/test
得到的输出是:
而我期望显示正常的HTML页面!
英文:
I've the below code:
package main
import (
"fmt"
htmlTempl "html/template"
"log"
"net/http"
)
var templatesHtml *htmlTempl.Template
var err error
func init() {
fmt.Println("Starting up.")
templatesHtml = htmlTempl.Must(htmlTempl.ParseGlob("templates/*.html"))
}
func test(w http.ResponseWriter, r *http.Request) {
err = templatesHtml.ExecuteTemplate(w, "other.html", nil)
if err != nil {
log.Fatalln(err)
}
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
http.HandleFunc("/test", test)
server.ListenAndServe()
}
And my templates are:
// Content of base.html:
{{define "base"}}
<html>
<head>{{template "head" .}}</head>
<body>{{template "body" .}}</body>
</html>
{{end}}
And
// Content of other.html:
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}
The output I got at http://127.0.0.1:8080/test
is:
While I was expecting normal HTML page to be displayed!
答案1
得分: 0
感谢mkoprivs提供的评论,错误在于使用//
作为注释标记,通过将其替换为HTML内容注释标记来解决了该问题,如下所示:
<!-- Content of other.html: -->
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}
现在一切都正常工作了。
英文:
Thanks to the comments provided by mkoprivs the error was in using //
as comment markers, it had be solved by replacing them with the html content comment marker as below:
<!-- Content of other.html: -->
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}
And it is working fine now.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论