Dynamically Update Template Partials in Go
In Go, the ability to refresh a portion of a template when a variable is modified is not inherently supported. To achieve this functionality, a custom solution must be implemented.
Implementation Steps:
Steps in Detail:
Template Refactoring:
{{define "Addresses"}} <ul> {{range $key, $value := .Addresses}} <li>{{ $key }}: {{ $value }}</li> {{end}} </ul> {{end}}
Handler Modification:
import "net/http" func AddressesHandler(w http.ResponseWriter, r *http.Request) { data := map[string]string{"Addresses": []string{"Address1", "Address2"}} t, err := template.New("AddressesTemplate").Parse("{{define "Addresses"}}{{.Addresses}}{{end}}") if err != nil { http.Error(w, http.StatusInternalServerError.String(), http.StatusInternalServerError) return } err = t.ExecuteTemplate(w, "Addresses", data) if err != nil { http.Error(w, http.StatusInternalServerError.String(), http.StatusInternalServerError) return } }
Client-Side Implementation:
var addressesElement = document.getElementById("addresses"); function refreshAddresses() { var xhr = new XMLHttpRequest(); xhr.open("GET", "/addresses", true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { addressesElement.outerHTML = xhr.responseText; } }; xhr.send(); }
Alternative Framework:
Gowut is a Go web framework that provides similar functionality for dynamic partial updates in web pages.
The above is the detailed content of How to Dynamically Update Template Partials in Go?. For more information, please follow other related articles on the PHP Chinese website!