DEV Community

Go4WebDev
Go4WebDev

Posted on • Edited on

Flicker free HTML forms using Go templates

When it comes to creating and populating HTML forms, there are many choices. The pivotal question: Should the form be crafted on the server or the client side? After some considerations, I've chosen a different approach. Something like "SSR Hybrid method."

How It Works:

  1. The Go render a HTML template form.
  2. During the rendering, data injected into the form.
  3. Labels are translated to the user's language.
  4. The page is then send to memory buffer
  5. Injected into the HTML body.
  6. The form is fetched and integrated into the innerHTML.

The Go func that make this possible sending REST string from Javascript fetch() tsk/view/1

// write form to buffer an send to html body
func get_card(w http.ResponseWriter, module string, mode string, val string) {
    page := module + "_" + mode // form name
    data := json2map4id(module, val) // call the API
    var buf bytes.Buffer 
    tpl.ExecuteTemplate(&buf, page, data) // Render to buffer
    fmt.Fprint(w, buf.String()) // write to html body
}
Enter fullscreen mode Exit fullscreen mode

Benefits of the SSR Hybrid Approach:

Safety The hybrid approach enhances security by reducing exposure of APIs to the internet directly, thanks to Go's compiled nature.

Speed & Flicker-Free Experience By optimizing initial page load times with Server-Side Rendering and subsequently employing JavaScript for seamless updates, users experience fast interactions without flickers.

Maintenance Simplified Combining related forms into single HTML templates streamlines maintenance and curbs complexity, even as your project grows.

Translation Go's HTML templating makes multilingual support simpler. All translations are handled server-side, ensuring global accessibility.

Seamless Form Switching The hybrid technique facilitates dynamic switches between forms, delivering a polished and uninterrupted user journey.

Check the "SSR Hybrid method" here in action. Code snippets attached.

Top comments (0)