Home >Backend Development >Golang >Can Go Templates Be Dynamically Partially Refreshed?
Dynamic Partial Template Refresh in Go
Question:
Is it feasible to dynamically refresh only a specific portion of a Go template when a variable updates?
Answer:
While the default template engine in Go doesn't natively support this feature, a custom implementation is possible. Here's a step-by-step guide:
1. Template Refactoring:
Separate the template that renders the Address array into a distinct template using the {{define "name"}} and {{template "name"}} actions.
2. Handler Modification/Creation:
Create a handler that exclusively executes the standalone Address template and outputs its HTML directly to the response. This handler can either handle both the full page and partial template, or it can be dedicated solely to the Address template.
3. Client-Side Modification:
When the Address array needs to be updated, trigger an AJAX call to the handler that renders the Address template. Upon receiving the response, replace the content within the wrapper tag of the Address element with the response HTML.
Here's a sample JavaScript code for the AJAX call and DOM manipulation:
var e = document.getElementById("addressees"); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { e.outerHTML = xhr.responseText; } } xhr.open("GET", "path-to-addresses-render", true); try { xhr.send(); } catch (err) { // Handle error }
Additional Note:
Third-party libraries such as Gowut provide similar functionality for partial template refresh. For further reference, consult the Gowut source code, specifically the rerenderComp() JavaScript function within the js.go file.
The above is the detailed content of Can Go Templates Be Dynamically Partially Refreshed?. For more information, please follow other related articles on the PHP Chinese website!