javascript - Dynamically refresh a part of the template when a variable is updated golang -
in golang, possible refresh part of template when variable updated ? can find in angular.js instance.
basically in code, lookup adresses postcode in ajax, display list of addr found postcode.
at moment, ajax calls go routine. don't want result in js , build html result of ajax call.
i like, if possible, update addresses value (it's array) build list of addr dynamically.
any clue ?
the template engine not support out-of-the-box.
so have implement yourself. it's not hard. here steps should follow achieve it:
1. refactor templates
separate template renders addresses on own using {{define "name"}}
action. may put in different template file , include in current place using {{template "name"}}
action, or may leave in original place , use new {{block "name" pipeline}} t1 {{end}}
action (introduced in go 1.6) defines template , executes @ once.
2. modify/create handlers
make sure have handler executes new template renders addressees. result of executing addressees template should sent directly output (w http.responsewriter
).
note may use 1 handler execute both "full" page template , addressees template (e.g. deciding based on url parameter), or may have 2 distinct handlers, it's you.
3. modify client side
now @ client side when want refresh / rerender addressees, make ajax call handler executes , renders addressees template.
when ajax call completes, may use response text of ajax call replace html content of wrapper tag of addressees.
it may this:
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 }
gowut (which web framework building single-page web applications using pure go) similar update parts of web page without full page reload (although doesn't use templates @ back-end side). (disclosure: i'm author of gowut.)
you may check out exact javascript code how gowut in js.go
file (look rerendercomp()
javascript function).
Comments
Post a Comment