首页 > 解决方案 > golang模板双父上下​​文

问题描述

我正在尝试从双父上下文访问变量。我的代码是:

dotColumnBlock

// 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

示例:游乐场

标签: go

解决方案


来自https://golang.org/pkg/text/template/#hdr-Variables

模板调用不会从其调用点继承变量。

但是,您可以通过注册一个函数来模拟全局变量。

t := template.Must(template.New("main").
     Funcs(template.FuncMap{
         "Global": func() string {return "true"},
     }).
     Parse(`...`))

然后在您的模板代码中,您只需使用{{Global}}您需要访问“全局”值的任何地方。

https://play.golang.org/p/oOmWqOIKFx5


推荐阅读