How to use scriptlets in HTMLOutput in Google Apps Script

谁都会走 提交于 2020-07-04 09:53:13

问题


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();
}

回答1:


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

I got it to work. Here is how you need to change your code:

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() // evaluate MUST come before setting the NATIVE mode
    .setSandboxMode(HtmlService.SandboxMode.NATIVE);

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



来源:https://stackoverflow.com/questions/27510858/how-to-use-scriptlets-in-htmloutput-in-google-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!