Golang 模板 - 使用模板变量作为范围循环内的全局变量

标签 go go-templates template-variables

我会尽量让这件事变得简单。 我在 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 '$' 以及抛出的 panic 。

目前我正在尝试的是完全不可能的,还是我缺少一些技巧?

谢谢:)

最佳答案

您应该简单地创建一个包含问题数组的 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

此外,如果您想要/需要添加特定于模板渲染过程的数据,您应该为此目的定义一个“丰富的”问题结构,并在将其传递给模板执行之前转换您的模型。这可以用于静态已知的额外数据(作为 RichIssue 的简单成员)和动态加载的数据(作为 map 的键/值)。

这是一个显示上述建议的扩展示例:

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

关于Golang 模板 - 使用模板变量作为范围循环内的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41534192/

相关文章:

json - 如何在 golang 中轻松编辑 JSON 类型(如 Node.js)

json - 解析嵌套的 json 文件

oop - golang - 树结构抽象

kubernetes - 使用 GoLang 模板模拟默认的 Kubernetes CLI 输出

html - 如何在 GoLand 或 PyCharm IDE 中打开与 html 文件相同的 .tmpl 文件?

docker - 如何列出网络; docker 容器附加到使用格式模板?

c++ - 非静态模板成员 : possible?

c++ - 为什么我必须特化递归模板变量?

Golang 在交叉编译时无法在 x86_64 机器上链接 aarch64/arm64 二进制文件