diff --git a/server/web/templatefunc.go b/server/web/templatefunc.go index 24f28502..f7cce06a 100644 --- a/server/web/templatefunc.go +++ b/server/web/templatefunc.go @@ -26,6 +26,7 @@ import ( "strings" "time" + "github.com/beego/beego/v2/core/logs" "github.com/beego/beego/v2/server/web/context" ) @@ -310,7 +311,8 @@ func RenderForm(obj interface{}) template.HTML { return template.HTML(strings.Join(raw, "
")) } -// renderFormField returns a string containing HTML of a single form field. +// renderFormField returns a string containing HTML of a single form field. In case of select fType, it will retrun +// select tag with options. Value for select fType must be comma separated string which are use are func renderFormField(label, name, fType string, value interface{}, id string, class string, required bool) string { if id != "" { id = " id=\"" + id + "\"" @@ -329,6 +331,25 @@ func renderFormField(label, name, fType string, value interface{}, id string, cl return fmt.Sprintf(`%v`, label, id, class, name, fType, value, requiredString) } + if fType == "select" { + valueStr, ok := value.(string) + if !ok { + logs.Error("for select value must comma separated string that are the options for select") + return "" + } + + var selectBuilder strings.Builder + selectBuilder.WriteString(fmt.Sprintf(`%v
`, label, id, class, name)) + + for _, option := range strings.Split(valueStr, ",") { + selectBuilder.WriteString(fmt.Sprintf(`
`, option, option)) + } + + selectBuilder.WriteString(``) + + return selectBuilder.String() + } + return fmt.Sprintf(`%v<%v%v%v name="%v"%v>%v`, label, fType, id, class, name, requiredString, value, fType) } diff --git a/server/web/templatefunc_test.go b/server/web/templatefunc_test.go index 403a8547..24116378 100644 --- a/server/web/templatefunc_test.go +++ b/server/web/templatefunc_test.go @@ -205,13 +205,13 @@ func TestRenderForm(t *testing.T) { ID int `form:"-"` Name interface{} `form:"username"` Age int `form:"age,text,年龄:"` - Sex string + Sex string `form:"sex,select"` Email []string Intro string `form:",textarea"` Ignored string `form:"-"` } - u := user{Name: "test", Intro: "Some Text"} + u := user{Name: "test", Intro: "Some Text", Sex: "Male,Female"} output := RenderForm(u) if output != template.HTML("") { t.Errorf("output should be empty but got %v", output) @@ -220,7 +220,10 @@ func TestRenderForm(t *testing.T) { result := template.HTML( `Name:
` + `年龄:
` + - `Sex:
` + + `Sex:
` + `Intro: `) if output != result { t.Errorf("output should equal `%v` but got `%v`", result, output)