Search code examples
htmlgoogle-apps-scriptweb-applications

How to use scriptlets in HTMLOutput in Google Apps Script


I'm loading a modal dialog with:

 var html = HtmlService.createHtmlOutputFromFile('File')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME)
    .setWidth(1000)
    .setHeight(700);

 SpreadsheetApp.getUi() 
    .showModalDialog(html, 'My Page');

Now, in File.HTML, I want to load another HTML file with CSS settings, how do I do that?

I've tried including it as in HtmlTemplate using scriptlets but it doesn't work:

<?!= include('File'); ?>

EDIT:

I have defined the include function in code.gs:

function include (file) {
  return HtmlService.createTemplateFromFile(file).evaluate().getContent();
}

Solution

  • The problem is that you are using:

    createHtmlOutputFromFile
    

    instead of:

    createTemplateFromFile
    

    You need to create a template:

    This is what you are seeing:

    Include with Dialog

    The scriptlet is not running, but being interpreted as text.

    This is what you want to see:

    Include that works

    Here is how the code should be:

    Code.gs

    // Use this code for Google Docs, Forms, or new Sheets.
    function onOpen() {
      SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
          .createMenu('Dialog')
          .addItem('Open', 'openDialog')
          .addToUi();
    }
    
    function openDialog() {
      var html = HtmlService.createTemplateFromFile('index')
        .evaluate();//This is necessary
    
        SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
        .showModalDialog(html, 'Dialog title');
    }
    
    function include(File) {
      return HtmlService.createHtmlOutputFromFile(File).getContent();
    };
    

    index.html

    <?!= include('File'); ?>
    
    Hello, world!
    <input type="button" value="Close"
      onclick="google.script.host.close()" />
    

    File.html

    <div>
        This is a test. it worked!
    </div>
    

    Basically, you need to change:

    var html = HtmlService.createHtmlOutputFromFile('index')
    

    to:

    var html = HtmlService.createTemplateFromFile('index')
    

    Create a TEMPLATE from file.

    And I also changed the code to this:

    function openDialog() {
      var html = HtmlService.createTemplateFromFile('index')
        .evaluate()
        .setSandboxMode(HtmlService.SandboxMode.IFRAME);
    

    Original answer:

    include is not something like a keyword or a built in function. You need to create a function in a .gs script file named include.

        function include(filename) {
          return HtmlService.createHtmlOutputFromFile(filename).getContent();
        };
    

    Also, you can't mix the HTML Service and the UI Service. I don't know if that's what you are trying to do, but I thought I'd mention it.

    What you want to accomplish is describe in the documentation here:

    Documentation - Best Practices