我会尽量让这个变得简单。 我在Golang中有两个变量,它们被解析为模板文件。
这是我的Golang代码,它声明了变量:
for _, issue := range issues {
issueIDStr := strconv.Itoa(*issue.ID)
parse[*issue.ID] = issueIDStr
parse[issueIDStr+"-label"] = "blah blah"
}
然后在我的HTML文件中:
{{ range .issues }}
<!-- Here I want to use the current issue's ID as a global variable which is outside the range loop -->
<!-- According to the Golang doc which says the following:
When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.
I can use $.Something to access a variable outside my range loop right...
but how can I use a template variable as a global variable? I tried the following which doesn't work.
{{ $ID := .ID }}
<p>{{ index $.$ID "author" }}</p>
{{ end }}
运行此代码后,我收到错误:bad character U+0024 '$'
以及引发的恐慌。
我目前的尝试是完全不可能的,还是我缺少一些技巧?
谢谢:)
答案 0 :(得分:0)
您只需创建一个包含issues数组的map [string] interface {},然后将其用作模板执行数据。
然后,您可以循环查看问题并直接访问其问题。模板中的成员。
这是一个小小的完整示例:
const t = `
{{ range .issues }}
issue: {{ .ID }}
author: {{ .Author }}
{{ end }}
`
type Issue struct {
ID int
Author string
}
func main() {
issues := []Issue{{1, "Pepe"}, {2, "Cholo"}}
data := map[string]interface{}{"issues": issues}
tpl := template.Must(template.New("bla").Parse(t))
tpl.Execute(os.Stdout, data)
}
哪个输出:
issue: 1
author: Pepe
issue: 2
author: Cholo
此外,如果您希望/需要添加特定于模板渲染过程的数据,您应该定义一个&#34; rich&#34;为此目的发出struct并在将模型传递给模板执行之前转换模型。这可以对静态已知的额外数据(作为RichIssue的简单成员)和动态加载的数据(作为地图的键/值)进行。
以下是展示上述建议的扩展示例:
const t = `
{{ range .issues }}
issue: {{ .ID }}
author: {{ .Author }}
static1: {{ .Static1 }}
dyn1: {{ .Data.dyn1 }}
{{ end }}
`
type Issue struct {
ID int
Author string
}
type RichIssue struct {
Issue
Static1 string // some statically known additional data for rendering
Data map[string]interface{} // container for dynamic data (if needed)
}
func GetIssueStatic1(i Issue) string {
return strconv.Itoa(i.ID) + i.Author // whatever
}
func GetIssueDyn1(i Issue) string {
return strconv.Itoa(len(i.Author)) // whatever
}
func EnrichIssue(issue Issue) RichIssue {
return RichIssue{
Issue: issue,
Static1: GetIssueStatic1(issue),
// in this contrived example I build "dynamic" members from static
// hardcoded strings but these fields (names and data) should come from
// some kind of configuration or query result to be actually dynamic
// (and justify being set in a map instead of being simple static
// members as Static1)
Data: map[string]interface{}{
"dyn1": GetIssueDyn1(issue),
"dyn2": 2,
"dyn3": "blabla",
},
}
}
func EnrichIssues(issues []Issue) []RichIssue {
r := make([]RichIssue, len(issues))
for i, issue := range issues {
r[i] = EnrichIssue(issue)
}
return r
}
func main() {
issues := []Issue{{1, "Pepe"}, {2, "Cholo"}}
data := map[string]interface{}{"issues": EnrichIssues(issues)}
tpl := template.Must(template.New("bla").Parse(t))
tpl.Execute(os.Stdout, data)
}
产生以下输出:
issue: 1
author: Pepe
static1: 1Pepe
dyn1: 4
issue: 2
author: Cholo
static1: 2Cholo
dyn1: 5