I am referring to this article about templated HTML and scriptlets with Google Apps Script: https://developers.google.com/apps-script/guides/html/templates
It is written how to call an Apps Script function and load the data when loading the html page:
Code.gs:
function doGet() {
return HtmlService
.createTemplateFromFile('Index')
.evaluate();
}
function getData() {
return SpreadsheetApp
.openById('1234567890abcdefghijklmnopqrstuvwxyz')
.getActiveSheet()
.getDataRange()
.getValues();
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<? var data = getData(); ?>
<table>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</body>
</html>
Question:
Is it possible to update the scriptlets without refreshing the whole page?
For example to implement a button and call the getData() function to load new data from the spreadsheet to the html?
Update:
I have adjusted the code with a simple button and a code to call the getData() function again and update the table. But of course doing it this way the for loop gets lost. Better would be to reload the whole code.
Is there a way to re-evaluate the whole page?
Any ideas?
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button type="button" onclick="Refresh()">Refresh</button>
<? var data = getData(); ?>
<table id="datatable">
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</body>
<script>
function Refresh(){
google.script.run.withSuccessHandler(update).withUserObject(this).getData();
}
function update(returnValue){
document.getElementById("datatable").innerHTML= returnValue
}
</script>
</html>
google.script.runRemember, however, that because template code executes before the page is served to the user, these techniques can only feed initial content to a page. To access Apps Script data from a page interactively, use the google.script.run API instead.