如何在Google Apps脚本中的HTMLOutput中使用scriptlet

Nun*_*ira 3 html google-apps-script

我正在加载一个模态对话框:

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

 SpreadsheetApp.getUi() 
    .showModalDialog(html, 'My Page');
Run Code Online (Sandbox Code Playgroud)

现在,在File.HTML中,我想用CSS设置加载另一个HTML文件,我该怎么做?

我已尝试将其包含在HtmlTemplate使用scriptlet中,但它不起作用:

<?!= include('File'); ?>
Run Code Online (Sandbox Code Playgroud)

编辑:

我在code.gs中定义了include函数:

function include (file) {
  return HtmlService.createTemplateFromFile(file).evaluate().getContent();
}
Run Code Online (Sandbox Code Playgroud)

Ala*_*lls 8

这就是你所看到的:

包括对话框

scriptlet未运行,但被解释为文本.

这是你想看到的:

包含有效

我得到了它的工作.以下是您需要更改代码的方法:

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() // evaluate MUST come before setting the NATIVE mode
    .setSandboxMode(HtmlService.SandboxMode.NATIVE);
    SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
    .showModalDialog(html, 'Dialog title');
}

function include(File) {
  return HtmlService.createHtmlOutputFromFile(File).getContent();
};
Run Code Online (Sandbox Code Playgroud)

的index.html

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

Hello, world!
<input type="button" value="Close"
  onclick="google.script.host.close()" />
Run Code Online (Sandbox Code Playgroud)

File.html

<div>
    This is a test. it worked!
</div>
Run Code Online (Sandbox Code Playgroud)

基本上,你需要改变:

var html = HtmlService.createHtmlOutputFromFile('index')
Run Code Online (Sandbox Code Playgroud)

至:

var html = HtmlService.createTemplateFromFile('index')
Run Code Online (Sandbox Code Playgroud)

从文件创建TEMPLATE.

我还将代码更改为:

function openDialog() {
  var html = HtmlService.createTemplateFromFile('index')
    .evaluate() // evaluate MUST come before setting the NATIVE mode
    .setSandboxMode(HtmlService.SandboxMode.NATIVE);
Run Code Online (Sandbox Code Playgroud)

原始答案:

include不是像一个keyword或内置的功能.您需要在.gs名为的脚本文件中创建一个函数include.

    function include(filename) {
      return HtmlService.createHtmlOutputFromFile(filename).getContent();
    };
Run Code Online (Sandbox Code Playgroud)

此外,您不能混合HTML服务和UI服务.我不知道你是不是想做什么,但我想我会提到它.

你想要完成的是在这里的文档中描述:

文档 - 最佳实践