Use project Javascript and CSS files in a Google Apps Script web app?

后端 未结 5 996
南方客
南方客 2020-12-08 08:40

If I create a simple HTML web app in Google Apps Script, like this:

function doGet() {
    return HtmlService.createHtmlOutputFromFile(\"index.html\");
}
         


        
5条回答
  •  误落风尘
    2020-12-08 09:06

    You can't have simple js or css files in the project so what you do instead is create html files that contain it, and preferably you place the < script>< /script> or < style> inside those files.

    So you might have a file a file named myscript.js.html with the following content:

    
    

    Now you put this line in the html where you want the asset to be included

    Put this in the html where you want to include the asset:

    
    

    Notice that the ".html" in the filename is omitted.

    If you're going to include a number of assets it might be a good idea to make a helper-function. You can put the following function in your code (gs-file)

    function include(filename) {
        return HtmlService.createTemplateFromFile(filename).getRawContent();
    }
    

    Then the line above can be changed to:

    
    

    Finally, you also need to call the evaluate()-method of the HTMLTemplate or else the code inside in the html file wont be evaluated. So if you're serving the html file like this for instance:

    var html=HtmlService.createTemplateFromFile('repeatDialog');
    SpreadsheetApp.getUi().showModalDialog(html, 'foo');
    

    You simply need to change it to:

    var html=HtmlService.createTemplateFromFile('repeatDialog').evaluate();
    SpreadsheetApp.getUi().showModalDialog(html, 'foo');
    

    If you were using createHtmlOutputFromFile and not createTemplateFromFile before then you should know that evaluate() returns htmlOutput so if you're wondering where to put things like .setWidth() then it's after the evaluate() call.

提交回复
热议问题