go - 如何将基础模板文件用于 golang html/模板?

标签 go

拥有 gin-gonic 网络应用程序。

有3个文件:

1) base.html -- 基础布局文件

<!DOCTYPE html>
<html lang="en">
<body>

header...

{{template "content" .}}

footer...

</body>
</html>

2) page1.html, for/page1

{{define "content"}}
<div>
    <h1>Page1</h1>
</div>
{{end}}
{{template "base.html"}}

3) page2.html,用于/page2

{{define "content"}}
<div>
    <h1>Page2</h1>
</div>
{{end}}
{{template "base.html"}}

问题是/page1 和/page2 使用一个模板 - page2.html。我想我对这样的结构有误解:{{define "content"}}, {{template "base.html"}}

请举例说明如何在 golang 中使用基本布局?

最佳答案

只要将模板与“内容”一起解析,就可以使用 base.html,如下所示:

基础.html

{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<body>

header...

{{template "content" .}}

footer...

</body>
</html>
{{end}}

page1.html

{{define "content"}}
I'm page 1
{{end}}

page2.html

{{define "content"}}
I'm page 2
{{end}}

然后 ParseFiles 使用 ("your-page.html", "base.html") 和 ExecuteTemplate 使用您的上下文。

tmpl, err := template.New("").ParseFiles("page1.html", "base.html")
// check your err
err = tmpl.ExecuteTemplate(w, "base", yourContext)

关于go - 如何将基础模板文件用于 golang html/模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36617949/

相关文章:

go - 基于接口(interface)抽象实现一个 'Stringer'

go - 如何在URL中转义句点字符

Postgresql 参数问题 $1

go - 如何探索 go 包中的函数

go - 使用管道与程序进程通信

http - golang : strategies to prevent connection reset by peer errors

templates - golang template.Execute 和结构嵌入

go - 在 Go 中将货币从 float 转换为整数的最佳方法是什么?

google-app-engine - 403 Forbidden 本地 Google Cloud Storage 调用

string - 如何将 Go 字符串文字代码转换为其值?