go应该如何处理html的select标签

在html的select标签上碰到难题. 我目前是这么处理:

1. 从数据库中取到选中的id

2. 新建一个struct:

type Sex struct {
        SexId   string
        SexVaule string
        Selected   bool
}

3. 再建立一个map:

var sexs=map[string]Sex{"1":Sex{"1","男",false},"2":Sex{"2","女",false}}

最后通过比对map key与id,相同时Selected设为true

4. html 输出:

  <select name="sex">
        {{range .sexs}}
           <option value="{{.SexId}}" {{if .Selected}}selected="selected"{{end}}>{{.SexValue}}</option>
       {{end}}
 </select>

这种方法处理起来很麻烦,请问有其他更简便的方法吗?

阅读 5.9k
1 个回答

给 html/template 注册一个新的函数即可 (下面只是一个例子,一些细节的 escape 还没做)

    foobar.AddFunc("OptionsForSelect", func(m interface{}, def string) template.HTML {
        var html string

        switch m.(type) {
        case []string:
            for k, v := range m.([]string) {
                if v == "" {
                    continue
                }

                ks := strconv.Itoa(k)
                html += `<option`
                if ks == def {
                    html += ` selected `
                }

                html += ` value="` + ks + `">` + v + `</option>`
            }
        case []map[string]string:
            for _, v := range m.([]map[string]string) {
                html += `<option`
                if v["value"] == def {
                    html += ` selected `
                }

                html += ` value="` + v["value"] + `">` + v["name"] + `</option>`
            }
        }

        return template.HTML(html)
    })

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题