Reputation: 535
I use CreateTemplateFromFile and push a variable inside my template. My template file is including another file, but I'm not able to push this variable in the second file embedded.
Here below what I've tried:
index.html:
<!DOCTYPE html>
<html>
<?!= include('header'); ?>
<?!= include('style'); ?>
<body>
...
</body>
<?!= include('script'); ?>
</html>
the script part of the index.html in a separate file:
<script>
function getData() {
$("#loadingMessage").html('Loading');
console.log('myContent:', <?= data ?>);
...
}
</script>
The doGet part of the Google apps script code:
var template = HtmlService.createTemplateFromFile('index');
template.data = myContent;
return template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
the variable is correctly pushed in index.html but not reach the script part. Any idea ? Maybe to include the script file as a template also ?
Upvotes: 1
Views: 811
Reputation: 26796
Google Apps Script features the method google.script.run that can be called from the JS part of a Web App. The methods allows to pass parameters to an Apps Script function and to assign the return value of the GAS function back to a JS function.
Sample:
.gs file
function doGet() {
var template = HtmlService.createTemplateFromFile('index');
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function myContent(input) {
var myContent="foo"+input;
return myContent;
}
HTML/js file
<html>
<head>
<base target="_top">
</head>
<body onload="getData()">
<script>
function getData() {
google.script.run.withSuccessHandler(proceedData).myContent("bar");
...
}
function proccedData(returnValue) {
var data = returnValue;
}
</script>
</body>
</html>
Remember, 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.
Because scriptlet code executes before the page is served, it can only run once per page; unlike client-side JavaScript or Apps Script functions that you call through google.script.run, scriptlets can't execute again after the page loads.^
In your case, if you want to use scriptlets, you either have to call a function or make your variable data
global, e.g.:
//global variable
var data=myContent;
function doGet() {
var temp=HtmlService.createTemplateFromFile("index.html");
return temp.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Also keep in mind:
Upvotes: 1