package templcomp import "reflect" import "log/slog" // Formable allows structs to implement custom form element generation code type Formable interface { ToFormElement() templ.Component } // GetForm tries to take any type and return form HTML templ ToForm(i any, postURL templ.SafeURL, name string) {
} // GetFormElement tries to take any type and return form field HTML templ ToFormField(x any, name string) { {{ xValue := reflect.ValueOf(x) xType := reflect.TypeOf(x) xIsFormable := xType.Implements(reflect.TypeOf((*Formable)(nil)).Elem()) }} if xIsFormable { {{ toFormElementMethod := xValue.MethodByName("ToFormElement") }} if toFormElementMethod.IsValid() { @toFormElementMethod.Call([]reflect.Value{})[0].Interface().(templ.Component) {{ return }} } else { {{ slog.Debug("invalid ToFormElement method on Formable", "xType", xType.Name()) }} } } switch xType.Kind() { case reflect.Func: {{ return }} case reflect.Pointer: if xValue.IsNil() { @ToFormField(reflect.New(xType.Elem()), name) } else { @ToFormField(xValue.Elem().Interface(), name) } case reflect.Struct:@ToFormField(fieldValue.Interface(), fieldName)
}unsupported: { xType.Name() }
} }