go - golang模板双父上下文
问题描述
我正在尝试从双父上下文访问变量。我的代码是:
dot
是ColumnBlock
:
// template content
<h4>{{.Global}}</h4> // he is fine
...
<div class="row">
<div class="col-12">{{template "column" .LeftColumn}}</div>
<div class="col-12">{{template "column" .RightColumn}}</div>
</div>
// template column
{{range .Columns}}
<div id="x-{{$.Kind}}-{{.ID}}">{{.Text}} - {{$.Global}}</div> // here Global is unavailable.
{{end}}
去:
type Column struct {
ID int
Text string
}
type ColumnList struct {
Kind string
Columns []Column
}
type ColumnBlock struct {
Global bool
LeftColumn ColumnList
RightColumn ColumnList
}
我如何访问.Global
变量column template
?
示例:游乐场
解决方案
来自https://golang.org/pkg/text/template/#hdr-Variables:
模板调用不会从其调用点继承变量。
但是,您可以通过注册一个函数来模拟全局变量。
t := template.Must(template.New("main").
Funcs(template.FuncMap{
"Global": func() string {return "true"},
}).
Parse(`...`))
然后在您的模板代码中,您只需使用{{Global}}
您需要访问“全局”值的任何地方。
推荐阅读
- jspdf - 如何使用 JSPDF 在 pdf 中添加水印?
- python - 如何使用 Python 将不同的列写入 CSV
- python - 使用python以正确的格式将列表插入csv
- javascript - 用对象中的相对变量替换以“@”开头的文本 - Javascript
- javascript - 在 IIS 服务器上从 NAS 访问数据
- b-tree - GFS 检查点的结构
- spring - Spring:ApplicationEventPublisher @TransactionalEventListener 事件未触发
- javascript - 修改后如何替换 URLSearchParams 并获取完整 URL
- mongodb - MongoDB 在运行“mongod”时遇到配置问题
- laravel-8 - 尝试在种子文件中将“simple_html_dom.php”连接到 laravel 项目。我遇到了错误“preg_match():编译失败”