Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Apps Script - HTML service "createTemplateFromFile" not usable from within App (spreadsheet, etc.)?

The docs for HtmlService don't state that this shouldn't work, but it seems that the template approach is limited to web app Apps Script projects.

I am attempting to use the HTMLService to create a UI within a SpreadSheet that can take some initial context, and then interact with the sheet. However, a runtime error is thrown when attempting to use "createTemplateFromFile" from within an Apps Script project in the sheet.

"changeDialog" referenced below is a simple file in the Apps Script project with placeholder markup:

<h2> fieldName </h2>

The following code throws an exception "Invalid argument: userinterface" when invoked:

function showSidebar(){

  var html = HtmlService.createTemplateFromFile('changeDialog');
  html.evaluate();

    SpreadsheetApp.getUi() 
      .showSidebar(html);
}

UPDATE: Updated with the actual code that wasn't working. And...answered by [Mogsdad]. All of the template docs show the web page variant, with the "doGet()" method returning the results of ".evaluate()". I thought that the html object carried the internal state of the "evaluate" method. I turns out that you either set that result to another var, or just do the call in line in the .showSideBar(...) method:

  SpreadsheetApp.getUi() 
     .showSidebar(html.evaluate());

or...

  var evaluatedHtml = html.evaluate();
  SpreadsheetApp.getUi() 
      .showSidebar(evaluatedHtml);
like image 870
Matt Hessinger Avatar asked Nov 12 '14 19:11

Matt Hessinger


People also ask

How do you access a Google spreadsheet from the App script?

In the Apps Script editor, click Run > logNamesAndMajors. The first time you run the sample, it will prompt you to authorize access: Click the Continue button. Click the Accept button.

How do I add data to a Google spreadsheet using an app script?

The code uses the appendRow() method of the Sheet object to write a single row of data to the spreadsheet. To append a row, pass an array of values (corresponding to the columns) to the appendRow() method. For example, the code below appends a row containing two values: First name and Last name.


1 Answers

You need to evaluate() a template to create an HtmlOutput object.

function showSidebar(){

  var html = HtmlService.createTemplateFromFile('changeDialog');

  var a = "test";

    SpreadsheetApp.getUi() 
      .showSidebar(html.evaluate());
                        //////////
}

Since your changeDialog.html file contains no template tags, you could instead create an HTML file from it directly:

function showSidebar(){

  var html = HtmlService.createOutputFromFile('changeDialog');
                               //////

  var a = "test";

    SpreadsheetApp.getUi() 
      .showSidebar(html);
}
like image 191
Mogsdad Avatar answered Nov 05 '22 22:11

Mogsdad