Adding a property to an Html template gives error

2019-01-28 21:15发布

I am trying to retrieve the data from my Google Spreadsheet, but when I try to add the data object to my htmlTemplate object, I receive the error

'Object does not allow properties to be added or changed'

My code is pretty simple:

function showDialog() {
  var htmlTemplate = HtmlService.createHtmlOutputFromFile('index');

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var range = sheet.getDataRange();
  var values = range.getValues(); //get the spreadsheet data

  htmlTemplate.data = values; // error here
  ...
}

Could anyone tell me what is wrong with this?

2条回答
放我归山
2楼-- · 2019-01-28 21:25

Instead of createHtmlOutputFromFile(filename) use createTemplateFromFile(filename)

The above because the first returns a HtmlOutput object which not allow to add properties while the second returns a HtmalTemplate which allows to add properties.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-28 21:40

You can't add properties once you have already created the htmlOutput, rather you should populate properties in a template and then evaluate that template so that properties are consumed[if you're consuming] and then final htmlOutput is produced.

In terms of code something like this :

function showDialog() {
  //Create a template
  var htmlTemplate = HtmlService.createTemplateFromFile('index');

  //Fetch the data
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getDataRange().getValues();

  //Plug in those data in template
  htmlTemplate.data = values;

  //Finally evaluate the template, to produce the actually html from the template
  var htmlOutput = htmlTemplate.evaluate();

  //Return [if required]
  return htmlOutput;
}
查看更多
登录 后发表回答