【发布时间】:2021-10-21 08:51:11
【问题描述】:
我有以下代码:
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()
}
我的模板是:
// Content of base.html:
{{define "base"}}
<html>
<head>{{template "head" .}}</head>
<body>{{template "body" .}}</body>
</html>
{{end}}
和
// Content of other.html:
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}
我在http://127.0.0.1:8080/test 得到的输出是:
虽然我期待显示正常的 HTML 页面!
【问题讨论】:
-
//不是模板文件中的注释标记,正如您所想的那样。查看文档以了解如何在模板中编写 cmets。或者只是删除评论,它并没有真正增加任何价值,是吗?另一种选择,如果你必须在文件中保留//东西,将 other.html 文件的 html 内容包装在它自己的define操作中,就像你对 base.html 所做的那样,只要确保你通过ExecuteTemplate 方法生成的模板的正确名称。 -
@mkopriva 谢谢,它通过删除
/或<!-- -->评论它们起作用,使用define给出错误panic: template: other.html:5: unexpected <define> in command -
我假设你把它放错了地方,或者使用了错误的语法,没有理由第三个有效的
define(注意你在那个文件中已经有两个)应该突然开始失败。模板文件可以有多少个定义并没有限制。没有看到更新的文件,但我可以提供更多帮助。
标签: go