go标准库模版layout 示例

golist 694 1

If you define all your templates in a template-folder, you can easily parse the whole directory with:

template.Must(template.ParseGlob("YOURDIRECTORY/*"))

For example:

head.html

{{define "header"}}
     <head>
         <title>{{.Title}}</title>
     </head>
{{end}}

index.html

{{define "indexPage"}}
    <html>
    {{template "header" . }}
    <body>
        <h1>Index</h1>
    </body>
    </html>
{{end}}

main.go

package main

import(
    "html/template"
)

// compile all templates and cache them
var templates = template.Must(template.ParseGlob("YOURTEMPLATEDIR/*"))

func main(){
    ...
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {

    tc := make(map[string]interface{})
    tc["Title"] = "Home"
    tc["Body"] = "Home body"

    // you access the cached templates with the defined name, not the filename
    err := templates.ExecuteTemplate(w, "indexPage", tc)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}

You execute your indexPage-Template with templates.ExecuteTemplate(w, "indexPage", nil)

来源 http://stackoverflow.com/questions/17206467/go-how-to-render-multiple-templates-in-golang 1

该主题到 2016-02-25 10:06:35 共 1 条回复
g
golist #

另外一个参考:

base.tmpl:

{{ define "base" }}
<html>
<head>
    {{ template "title" . }}
</head>
<body>
    {{ template "scripts" . }}
    {{ template "sidebar" . }}
    {{ template "content" . }}
<footer>
    ...
</footer>
</body>
</html>
{{ end }}
// We define empty blocks for optional content so we don't have to define a block in child templates that don't need them
{{ define "scripts" }}{{ end }}
{{ define "sidebar" }}{{ end }}

index.tmpl:

{{ define "title"}}<title>Index Page</title>{{ end }}
// Notice the lack of the script block - we don't need it here.
{{ define "sidebar" }}
    // We have a two part sidebar that changes depending on the page
    {{ template "sidebar_index" }} 
    {{ template "sidebar_base" }}
{{ end }}
{{ define "content" }}
    {{ template "listings_table" . }}
{{ end }}

handle

import (
    "fmt"
    "html/template"
    "net/http"
    "path/filepath"
)

var templates map[string]*template.Template

// Load templates on program initialisation
func init() {
    if templates == nil {
        templates = make(map[string]*template.Template)
    }

    templatesDir := config.Templates.Path

    layouts, err := filepath.Glob(templatesDir + "layouts/*.tmpl")
    if err != nil {
        log.Fatal(err)
    }

    includes, err := filepath.Glob(templatesDir + "includes/*.tmpl")
    if err != nil {
        log.Fatal(err)
    }

    // Generate our templates map from our layouts/ and includes/ directories
    for _, layout := range layouts {
        files := append(includes, layout)
        templates[filepath.Base(layout)] = template.Must(template.ParseFiles(files...))
    }

}

// renderTemplate is a wrapper around template.ExecuteTemplate.
func renderTemplate(w http.ResponseWriter, name string, data map[string]interface{}) error {
    // Ensure the template exists in the map.
    tmpl, ok := templates[name]
    if !ok {
        return fmt.Errorf("The template %s does not exist.", name)
    }

    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    tmpl.ExecuteTemplate(w, "base", data)

    return nil
}

来源 https://elithrar.github.io/article/approximating-html-template-inheritance/ 3

登录发表评论

桂公网安备 45122402000014号