【发布时间】:2017-05-22 21:33:07
【问题描述】:
我会尽量简化。 我在 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 '$' 并引发恐慌。
我目前正在尝试的东西是完全不可能的,还是我缺少一些技巧?
谢谢:)
【问题讨论】:
-
你不能像 $.$ID 一样使用它,它不会像你预期的那样评估它。您可能必须以不同的方式构建它
-
你我使用全局地图并使用 ID 作为键
-
@Acidic,请添加显示您如何执行(...)模板的代码行。
标签: go go-templates template-variables