douyanlu7380 2018-04-28 20:12
浏览 143
已采纳

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

I am new to golang. I would like to pass multiple variables to html. So I have a type like:

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

pagevarible with passed the correct values

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
    }

And I want to pass both UserNames and Checks to html template, something like:

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

But it didn't work out. Can anyone correct my syntax? Thanks a lot.

  • 写回答

2条回答 默认 最新

  • dongxun1244 2018-04-28 21:31
    关注

    Range with an index variable, use that index to get the check:

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

    Range sets the cursor . to successive values of the slice. Use $ to reference the Checks field in the argument to the template.

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?