【发布时间】:2016-11-10 12:11:14
【问题描述】:
我正在用 GoLang 编写一个 Web 应用程序,没有使用任何框架。
例如,我正在尝试创建一个类似于 nodejs 中的布局的layout。
=== layout.html ====
{{ define "layout"}}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<link href="/static/style.css" rel="stylesheet" media="all" type="text/css">
</head>
<body>
{{ template "content"}}
</body>
</html>
{{ end }}
然后我在 home.html 中有一些内容
{{ define "content"}}
<h1>{{.Title}}</h1>
<div>This is a test</div>
{{ end }}
我对这种方法有 2 个问题
(1)我的执行模板代码,似乎没有将数据传递给内容
templates.ExecuteTemplate(w, "layout", &Page{Title: "Home", Body: nil})
(2) 如果我想拥有多个具有相同布局的页面,上述将不起作用,因为它没有指定要加载的内容。
有人可以解释一下在 GoLang 中使用 tempates 和“布局”的策略吗?
【问题讨论】:
-
使用
{{template "content" .}}将数据传递给子模板。 -
查看备选方案如何选择要包含的内容:How to use a field of struct or variable value as template name?
标签: go go-templates