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

In Golang, it is possible to refresh a part of a template when a variable is updated ? This is something that we can find in Angular.js for instance.

Basically in my code, I lookup adresses by a postcode in ajax, which display my list of addr found for this postcode.

Here is a sample of the template : enter image description here

At the moment, the ajax calls a GO routine. I don't want to get the result in the JS and build the html from the result of the ajax call.

I would like, if possible, to update only the Addresses value (it's an array) as I already build the list of addr dynamically.

Any clue ?

Answers:

Answer

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).

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.