栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用标准库可以在Go中嵌套模板吗?(Google App Engine)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用标准库可以在Go中嵌套模板吗?(Google App Engine)

是的,有可能。A

html.Template
实际上是一组模板文件。如果执行该集中定义的块,则该块有权访问该集中定义的所有其他块。

如果您自己创建此类模板集的映射,则基本上具有Jinja / Django提供的灵活性。唯一的区别是html /
template
包无法直接访问文件系统,因此您必须自己解析和编写模板。

考虑下面的示例,其中有两个不同的页面(“ index.html”和“ other.html”)都继承自“ base.html”:

// Content of base.html:{{define "base"}}<html>  <head>{{template "head" .}}</head>  <body>{{template "body" .}}</body></html>{{end}}// Content of index.html:{{define "head"}}<title>index</title>{{end}}{{define "body"}}index{{end}}// Content of other.html:{{define "head"}}<title>other</title>{{end}}{{define "body"}}other{{end}}

以及以下模板集图:

tmpl := make(map[string]*template.Template)tmpl["index.html"] = template.Must(template.ParseFiles("index.html", "base.html"))tmpl["other.html"] = template.Must(template.ParseFiles("other.html", "base.html"))

您现在可以通过调用来呈现“ index.html”页面

tmpl["index.html"].Execute("base", data)

您可以通过调用来呈现“ other.html”页面

tmpl["other.html"].Execute("base", data)

通过一些技巧(例如,模板文件的命名约定一致),甚至可以

tmpl
自动生成地图。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/417697.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号