在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>
这种方法处理起来很麻烦,请问有其他更简便的方法吗?
给 html/template 注册一个新的函数即可 (下面只是一个例子,一些细节的 escape 还没做)