1
votes

It is my understanding that global variables can be accessed from within Google Apps Script (GAS) Scriptlets. (See: https://developers.google.com/apps-script/guides/html/templates). So, in essence, I do something like this:

var myVariable;
function doGet() {
myVariable="Doug";
...
}

Thereafter, I am unable to access myVariable from within a GAS scriptlet. I am told that myVariable is undefined. I need to know how I can access values developed within doGet() from a GAS scriptlet. Any input would be greatly appreciated. Thanks.

   ... doug
1

1 Answers

2
votes

No, you cant. You should put your variables you want to use in the scriplet into the data of HtmlService instance. Example:

Code.gs:

function doGet() {
  var t = HtmlService.createTemplateFromFile('index');
  t.data = SpreadsheetApp
      .openById('1234567890abcdefghijklmnopqrstuvwxyz')
      .getActiveSheet()      
      .getDataRange()
      .getValues();
  return t.evaluate();
}

index.html:

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

(This was taken from the official docs here)

In your case:

Code.gs:

function doGet() {
  var t = HtmlService.createTemplateFromFile('index');
  t.data = "Doug"
  return t.evaluate();
}

index.html:

<?= data ?>