如何将多个变量传递给 Go HTML 模板

How to pass multiple variables to Go HTML template

我是 golang 的新手。我想将多个变量传递给 html。 所以我有这样的类型:

type Variables struct { 
    UserNames    []string  
    Checks       []string
}

传递了正确值的页面变量

var PageVars Variables
    PageVars = Variables{
        UserNames: ulist,
        Checks: check,
    }
    log.Println("ulist",ulist)
    err = tpl.Execute(w, PageVars) //execute the template and pass it to index page
    if err != nil { // if there is an error
        log.Print("template executing error: ", err) //log it on terminal
    }

我想将 UserNames 和 Checks 都传递给 html 模板,例如:

{{range .UserNames .Checks}}
{{.UserNames}}: <input type="checkbox" name="email" value={{. UserNames}} {{.Checks}}/><br />
{{end}}

但是没有成功。 谁能纠正我的语法? 非常感谢。

当您通过范围内的 . 引用字段时,它期望该字段是被范围内的项目的字段,因此在这种情况下

{{range .UserNames}}
{{$check := .Checks}}

它正在用户名列表中寻找当前实例的检查字段。如果 checks 与它分开(因为它出现在您的 PageVars 中),那么您可以使用 $ 对顶级对象的引用,例如

{{range .UserNames}}
{{$check := $.Checks}} 

您没有 post 执行模板的代码,但请确保您正在检查从它返回的错误。

带有索引变量的范围,使用该索引进行检查:

{{range $i, $user := .UserNames}}
{{$check := index $.Checks $i}}
{{$user}}: <input type="checkbox" name="email" value={{$user}} {{$check}}/><br />
{{end}}

Range 将光标 . 设置为切片的连续值。使用 $ 引用模板参数中的 Checks 字段。

playground example