如何在Google Apps Script的HTMLOutput中使用脚本片段

4

我正在使用以下代码加载模态对话框:

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

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

现在,在File.HTML中,我想加载另一个具有CSS设置的HTML文件,我该怎么做?
我尝试使用脚本包含它,但不起作用:HtmlTemplate
<?!= include('File'); ?>

编辑:

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

function include (file) {
  return HtmlService.createTemplateFromFile(file).evaluate().getContent();
}
1个回答

16

问题在于您正在使用:

createHtmlOutputFromFile

改为:

createTemplateFromFile

你需要创建一个模板:

这是你所看到的:

使用对话框进行包含

脚本块未运行,而是被解释为文本。

这是你想看到的:

有效的包含方式

以下是代码应该如何编写:

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>

基本上,您需要更改:

var html = HtmlService.createHtmlOutputFromFile('index')
to:
var html = HtmlService.createTemplateFromFile('index')

从文件创建模板

我也将代码更改为:

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

翻译后的答案:

include 不是像关键字或内置函数一样的东西。您需要在一个名为 .gs 的脚本文件中创建一个名为 include 的函数。

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

此外,您不能混合使用HTML服务和UI服务。我不知道您是否想这样做,但我想提一下。

您想要完成的内容在此文档中进行了描述:

文档 - 最佳实践


谢谢,请看我的编辑。我已经在code.gs中定义了include。它在侧边栏中运行良好,但当我打开模态对话框时,它只输入<?!= include('File'); ?>。 - user882670
1
没错,这个可以运行,而且也适用于新的IFRAME模式。 必须更好地理解模板和输出之间的区别。 - user882670

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接