我有
boilerplate.templ
、navbar.templ
和body.templ
。如何将这些模板文件嵌入到样板中?
我试过这个:
package views
css Base(){
background-color: #F4F2F3;
font-family: Arial, sans-serif;
}
navbarComponent:=navbar()
templ boilerplate(){
<html>
<head>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
{navbarComponent.render(nil,nil)}
</body>
</html>
}
这是一个示例,假设您正在询问 std 库:
templates/base.html
{{ define "body" }}{{ end }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Concerts</title>
<link rel="stylesheet" href="/static/styles.css">
</head>
<body>
{{ template "body" . }}
</body>
templates/about.html
{{ block "body" . }}
<h1>About page</h1>
{{ end }}
然后像这样执行模板:
//go:embed templates
var files embed.FS
...
var tmpl *template.Template
if condForJustAboutPage {
tmpl = template.Must(template.New("about.html").ParseFS(files, "templates/about.html"))
} else {
// return whole page: base + about.
tmpl = template.Must(template.New("base.html").ParseFS(files, "templates/about.html", "templates/base.html"))
}
err := tmpl.Execute(w, "")
if err != nil {
// todo handle this
return
}
我建议您查看 文档,以更好地了解块的工作原理([1] 中只是一个片段),以及 嵌套模板定义 的工作原理。
希望这有帮助!
[1]
{{block "name" pipeline}} T1 {{end}}
A block is shorthand for defining a template
{{define "name"}} T1 {{end}}
and then executing it in place
{{template "name" pipeline}}
The typical use is to define a set of root templates that are
then customized by redefining the block templates within.