diff --git a/templatefunc.go b/templatefunc.go index f51eaac4..ea98470a 100644 --- a/templatefunc.go +++ b/templatefunc.go @@ -327,7 +327,6 @@ func ParseForm(form url.Values, obj interface{}) error { return nil } - var unKind = map[reflect.Kind]bool{ reflect.Uintptr: true, reflect.Complex64: true, @@ -367,12 +366,30 @@ func RenderForm(obj interface{}) template.HTML { continue } - raw = append(raw, fmt.Sprintf(`%v`, - label, name, fType, fieldV.Interface())) + raw = append(raw, renderFormField(label, name, fType, fieldV.Interface())) } return template.HTML(strings.Join(raw, "
")) } +func renderFormField(label, name, fType string, value interface{}) string { + if isValidForInput(fType) { + return fmt.Sprintf(`%v`, label, name, fType, value) + } + + return fmt.Sprintf(`%v<%v name="%v">%v`, label, fType, name, value, fType) +} + +func isValidForInput(fType string) bool { + validInputTypes := strings.Fields("text password checkbox radio submit reset hidden image file button") + for _, validType := range validInputTypes { + if fType == validType { + return true + } + } + return false +} + + // parseFormTag takes the stuct-tag of a StructField and parses the `form` value. // returned are the form label, name-property, type and wether the field should be ignored. func parseFormTag(fieldT reflect.StructField) (label, name, fType string, ignored bool) { diff --git a/templatefunc_test.go b/templatefunc_test.go index a19d9bc5..373b11fa 100644 --- a/templatefunc_test.go +++ b/templatefunc_test.go @@ -148,9 +148,10 @@ func TestRenderForm(t *testing.T) { Sex string Email []string Intro string `form:",textarea"` + Ignored string `form:"-"` } - u := user{Name: "test"} + u := user{Name: "test", Intro: "Some Text"} output := RenderForm(u) if output != template.HTML("") { t.Errorf("output should be empty but got %v", output) @@ -160,12 +161,24 @@ func TestRenderForm(t *testing.T) { `Name:
` + `年龄:
` + `Sex:
` + - `Intro: `) + `Intro: `) if output != result { t.Errorf("output should equal `%v` but got `%v`", result, output) } } +func TestRenderFormField(t *testing.T) { + html := renderFormField("Label: ", "Name", "text", "Value") + if html != `Label: ` { + t.Errorf("Wrong html output for input[type=text]: %v ", html) + } + + html = renderFormField("Label: ", "Name", "textarea", "Value") + if html != `Label: ` { + t.Errorf("Wrong html output for textarea: %v ", html) + } +} + func TestParseFormTag(t *testing.T) { // create struct to contain field with different types of struct-tag `form` type user struct {