douqiao8032 2018-08-29 17:44
浏览 61
已采纳

ExecuteTemplate(template.ParseGlob)加载空白页

I'm trying to load template page.gohtml from folder cms/template. When trying to view in Firefox browser it load Blank.

handler.go file

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)
}

cmd/main.go file

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", cms.ServeIndex)

    fmt.Println("Server running at port 3000")
    go http.ListenAndServe(":3000", r)
    fmt.Scanln()
}

templates/page.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条回答 默认 最新

  • dtq81142 2018-08-30 02:28
    关注

    I found the issue when I used error handling.

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

    Which printed "no such template comments" while I was using defined "comment" inside comment.gohtml

    Sorry for posting this question, I recently started GoLang.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题