代码之家  ›  专栏  ›  技术社区  ›  STEEL

执行模板(模板.ParseGlob)加载空白页

  •  -2
  • STEEL  · 技术社区  · 7 年前

    page.gohtml 从文件夹 cms/template . 当尝试在Firefox浏览器中查看时,加载为空白。

    处理程序.go

    var Tmpl = template.Must(template.ParseGlob("../templates/*"))
    
    func ServeIndex(w http.ResponseWriter, r *http.Request) {
        p := &Page{
            Title:   "Go Projects CMS",
            Content: "Welcome to the Home Page!",
            Posts: []*Post{
                {
                    Title:         "Hello World!",
                    Content:       "Hey y'all, Thanks for coming",
                    DatePublished: time.Now(),
                },
                {
                    Title:         "This Has Comments",
                    Content:       "Atlassian Just Bought Trello...GO!",
                    DatePublished: time.Now().Add(-time.Hour),
                    Comments: []*Comment{
                        {
                            Author:        "Davy Jones",
                            Content:       "This is something to say about something",
                            DatePublished: time.Now().Add(-time.Hour / 2),
                        },
                    },
                },
            },
        }
        Tmpl.ExecuteTemplate(w, "page", p)
    }
    

    命令/main.go

    func main() {
        r := mux.NewRouter()
        r.HandleFunc("/", cms.ServeIndex)
    
        fmt.Println("Server running at port 3000")
        go http.ListenAndServe(":3000", r)
        fmt.Scanln()
    }
    

    模板/网页.gohtml

    {{ define "page" }}
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>{{ .Title }}</title>
        <link rel="stylesheet" href="https://unpkg.com/tachyons@4.10.0/css/tachyons.min.css"/>
    </head>
    <body class="w-100 sans-serif bg-white">
        <h1>Welcome</h1>
        <div class="baskerville pb5">
        {{ .Content }}
        {{if .Posts}}
            {{range .Posts}}
                {{template "post" .}}
            {{end}}
        {{end}}
        </div>
    </body>
    </html>
    {{ end }}
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   STEEL    7 年前

    我在使用错误处理时发现了这个问题。

    if err := Tmpl.ExecuteTemplate(w, "page", p); err != nil {
            log.Printf("Template error: %v", err)
            w.WriteHeader(http.StatusInternalServerError)
            return
        }
    

    在我使用的时候打印了“没有这样的模板注释” defined "comment" 里面 评论.gohtml

    很抱歉贴出这个问题,我最近开始GoLang。