Skip to content
Permalink
Browse files

03-Template-Advance template inheritance

  • Loading branch information...
bonfy committed Sep 7, 2018
1 parent 134267d commit e5fd3ef25bcc6874818621d06e68dee3d379778a
Showing with 60 additions and 18 deletions.
  1. +40 −2 main.go
  2. +13 −0 templates/_base.html
  3. +7 −0 templates/content/index.html
  4. +0 −16 templates/index.html
42 main.go
@@ -2,7 +2,9 @@ package main

import (
"html/template"
"io/ioutil"
"net/http"
"os"
)

// User struct
@@ -23,6 +25,41 @@ type IndexViewModel struct {
Posts []Post
}

// PopulateTemplates func
// Create map template name to template.Template
func PopulateTemplates() map[string]*template.Template {
const basePath = "templates"
result := make(map[string]*template.Template)

layout := template.Must(template.ParseFiles(basePath + "/_base.html"))
dir, err := os.Open(basePath + "/content")
if err != nil {
panic("Failed to open template blocks directory: " + err.Error())
}
fis, err := dir.Readdir(-1)
if err != nil {
panic("Failed to read contents of content directory: " + err.Error())
}
for _, fi := range fis {
f, err := os.Open(basePath + "/content/" + fi.Name())
if err != nil {
panic("Failed to open template '" + fi.Name() + "'")
}
content, err := ioutil.ReadAll(f)
if err != nil {
panic("Failed to read content from file '" + fi.Name() + "'")
}
f.Close()

This comment has been minimized.

Copy link
@AaronWharton

AaronWharton Dec 1, 2018

hello ,作者。我有个小小的建议,在 for 循环中使用 func () {}() 来包装里面文件操作的代码,保证使用 defer 不会产生延迟关闭文件的情况发生。具体可以查看 PR #bonfy/go-mega#2

tmpl := template.Must(layout.Clone())
_, err = tmpl.Parse(string(content))
if err != nil {
panic("Failed to parse contents of '" + fi.Name() + "' as template")
}
result[fi.Name()] = tmpl
}
return result
}

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
u1 := User{Username: "bonfy"}
@@ -34,8 +71,9 @@ func main() {
}

v := IndexViewModel{Title: "Homepage", User: u1, Posts: posts}
tpl, _ := template.ParseFiles("templates/index.html")
tpl.Execute(w, &v)

templates := PopulateTemplates()
templates["index.html"].Execute(w, &v)
})
http.ListenAndServe(":8888", nil)
}
@@ -0,0 +1,13 @@
<html>
<head>
{{if .Title}}
<title>{{.Title}} - blog</title>
{{else}}
<title>Welcome to blog!</title>
{{end}}
</head>
<body>
<div>Blog: <a href="/">Home</a></div>
{{template "content" .}}
</body>
</html>
@@ -0,0 +1,7 @@
{{define "content"}}
<h1>Hello, {{.User.Username}}!</h1>

{{range .Posts}}
<div><p>{{ .User.Username }} says: <b>{{ .Body }}</b></p></div>
{{end}}
{{end}}

This file was deleted.

0 comments on commit e5fd3ef

Please sign in to comment.
You can’t perform that action at this time.