Dynamically refresh a part of the template when a variable is updated golang

The template engine does not support this out-of-the-box.

So you have to implement it yourself. It’s not that hard. Here are the steps you should follow to achieve it:

1. Refactor your templates

Separate the template that renders the Addresses to be on its own by using a {{define "name"}} action. You may put it in a different template file and include it in its current place by using {{template "name"}} action, or you may leave it in the original place and use the new {{block "name" pipeline}} T1 {{end}} action (introduced in Go 1.6) which defines the template and executes it at once.

2. Modify/create handlers

Make sure you have a handler which executes only this new template that renders the Addressees. The result of executing the Addressees template should be sent directly to the output (w http.ResponseWriter).

Note that you may use 1 handler to execute both the “full” page template and only the Addressees template (e.g. deciding based on a URL parameter), or you may have 2 distinct handlers, it’s really up to you.

3. Modify client side

Now at client side when you want to refresh / rerender the Addressees, make an AJAX call to the handler that only executes and renders the Addressees template.

When this AJAX call completes, you may simply use the response text of the AJAX call to replace the HTML content of the wrapper tag of Addressees.

It may look something like 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 is a web framework for building single-page web applications using pure Go) does something similar to update only parts of the web page without full page reload (although it doesn’t use templates at the back-end side). (Disclosure: I’m the author of Gowut.)

You may check out the exact Javascript code how Gowut does it in its js.go file (look for the rerenderComp() Javascript function).

Leave a Comment