GO: Как отобразить несколько шаблонов в golang?
Создается один базовый шаблон.
С помощью этого сделанного first.html еще одного шаблона.
eg. :
var tmpl = template.Must(template.ParseFiles(
"templates/base.html",
"templates/first.html",
))
Но я также хочу добавить больше .html файлов для рендеринга.
Любая ссылка?
Ответы
Ответ 1
Если вы определяете все свои шаблоны в папке-шаблоне, вы можете легко проанализировать весь каталог с помощью
template.Must(template.ParseGlob("YOURDIRECTORY/*"))
Например:
head.html
{{define "header"}}
<head>
<title>Index</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) {
// you access the cached templates with the defined name, not the filename
err := templates.ExecuteTemplate(w, "indexPage", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
Вы выполняете свой шаблон indexPage с помощью templates.ExecuteTemplate(w, "indexPage", nil)
Ответ 2
Вы можете легко добавить больше .html файлов, просто добавив их в качестве аргументов:
var tmpl = template.Must(template.ParseFiles(
"templates/base.html",
"templates/first.html",
"templates/second.html",
))
Это работает отлично, пока первый и второй не определяют один и тот же шаблон.
Однако пакет шаблонов не позволяет динамический вызов шаблонов, используя значение конвейера для имени шаблона. Итак, если вы пытаетесь сделать что-то похожее на мой пример ниже, это не сработает.
Существуют некоторые обходные пути, и об этом обсуждается на Go-nuts. Но кажется, что пакет шаблонов спроектирован так, что у вас должен быть один объект *Template
на странице.
Неисправный пример попытки динамического вызова шаблона:
Ошибка: неожиданный ".Content" в вызове шаблона
package main
import (
"log"
"os"
"text/template"
)
const base= `<!DOCTYPE html>
<html>
<head><title>Title</title></head>
<body>
{{template .Content}}
</body>
</html>`
const first = `{{define "first"}}This is the first page{{end}}`
const second = `{{define "second"}}And here is the second{{end}}`
type View struct {
Content string
}
func main() {
var view = &View{ "first" } // Here we try to set which page to view as content
t := template.Must(template.New("base").Parse(base))
t = template.Must(t.Parse(first))
t = template.Must(t.Parse(second))
err := t.Execute(os.Stdout, view)
if err != nil {
log.Println("executing template:", err)
}
}
Код на play.golang.org
Ответ 3
часть 3 этого урока полезна:
http://golangtutorials.blogspot.co.nz/2011/11/go-templates-part-3-template-sets.html
Пример из учебника:
Полный файл шаблона - t1.tmpl
{{define "t_ab"}}a b{{template "t_cd"}}e f {{end}}
Файл, указанный выше, будет обрабатываться как шаблон с именем "t_ab". В нем есть "b/missing/e f", но в алфавите отсутствует пара букв. Для этого он намерен включить другой шаблон под названием "t_cd" (который должен быть в том же наборе).
Полный файл шаблона - t2.tmpl
{{define "t_cd"}} c d {{end}}
Файл, указанный выше, будет проанализирован как шаблон с именем "t_cd".
Полная программа
package main
import (
"text/template"
"os"
"fmt"
)
func main() {
fmt.Println("Load a set of templates with {{define}} clauses and execute:")
s1, _ := template.ParseFiles("t1.tmpl", "t2.tmpl") //create a set of templates from many files.
//Note that t1.tmpl is the file with contents "{{define "t_ab"}}a b{{template "t_cd"}}e f {{end}}"
//Note that t2.tmpl is the file with contents "{{define "t_cd"}} c d {{end}}"
s1.ExecuteTemplate(os.Stdout, "t_cd", nil) //just printing of c d
fmt.Println()
s1.ExecuteTemplate(os.Stdout, "t_ab", nil) //execute t_ab which will include t_cd
fmt.Println()
s1.Execute(os.Stdout, nil) //since templates in this data structure are named, there is no default template and so it prints nothing
}