在此示例中,我有一个 main.html 模板
<!DOCTYPE html>
<html>
<head>
<title>Backend</title>
<style>
html, body {height:100%}
</style>
</head>
<body>
<table border="1" width="100%" height="100%">
<tr>
<td colspan="2" class="td-header">
<h1>Google GO</h1>
</td>
</tr>
<tr>
<td class="td-right-content">
{{<parsed template from children>}}
</td>
</tr>
<tr>
<td colspan="2" class="td-header">
<h1>Footer</h1>
</td>
</tr>
</table>
</body>
</html>
子部分将填充
{{}}
与
<table>
<tr>
<th>
Name
</th>
<th>
Description
</th>
<th>
</th>
</tr>
{{range .}}
<tr>
<td>
{{.Name}}
</td>
<td>
{{.Description}}
</td>
<td>
<a href="/admin/forms/edit/?key={{.Key.Encode}}">Edit</a>
</td>
</tr>
{{end}}
</table>
在子部分的代码中解析后。 我这样做是为了消除多余的 html 和 css 并轻松管理设计。 谢谢大家!
最佳答案
Template
对象包含一个顶级模板(此处:父模板),它可以引用同一对象中关联的其他模板。模板有一个用于引用的名称。
这可能很棘手,因为当您使用ParseFiles
函数创建新对象时,每个模板都使用文件的基本名称来命名(并且似乎不可能更改该名称) )。如果给定主文件有多个可能的子文件,则这可能不切实际,因为您通常不想给它们提供相同的名称。
解决方案是手动将文件读取为字符串,然后将其添加到显式命名的模板中(IMO 有点麻烦,但您可以接受它)。
main_temp,_ := template.ParseFiles("main.html")
cont_s,_ := ioutil.ReadFile("content1.html")
// add a new associated template to main
cont_temp,_ := main_temp.New("content").Parse(string(cont_s))
g := Content{"Hi"}
main_temp.Execute(os.Stdout, &g)
(我跳过了示例的所有错误处理)
然后您可以在父页面中使用 {{template}}
指令:
{{template "content" .}}
(或任何管道,而不是 .
,它指的是赋予 main_temp
的整个对象)
参见text/template doc了解更多详情
关于google-app-engine - 将 html 模板合并到 GAE GO 基础模板中,这样结构就只有通用的 html/css 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14218711/