如何在Google Apps脚本的HTMLOutput中使用scriptlet [英] How to use scriptlets in HTMLOutput in Google Apps Script

查看:228
本文介绍了如何在Google Apps脚本的HTMLOutput中使用scriptlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下内容加载模式对话框:

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');

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

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

我尝试使用小脚本将其包含在HtmlTemplate中,但是它不起作用:

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

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

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

I have defined the include function in code.gs:

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

推荐答案

问题是您正在使用:

createHtmlOutputFromFile

代替:

createTemplateFromFile

您需要创建一个模板:

这是您所看到的:

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

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

这是您想看到的:

代码应为:

// 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')

收件人:

var html = HtmlService.createTemplateFromFile('index')

从文件创建模板.

我也将代码更改为此:

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

原始答案:

include不同于keyword或内置函数.您需要在名为include.gs脚本文件中创建一个函数.

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

此外,您不能混合使用HTML服务和UI服务.我不知道这是否是您要尝试的操作,但我想我已经提到了.

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:

文档-最佳做法

这篇关于如何在Google Apps脚本的HTMLOutput中使用scriptlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆