Search code examples
google-apps-scriptgoogle-sheetsgoogle-caja

HTML Service - Dropdown option list from GSheet


Into Google Apps script and HTML service

Code.gs 
function doGet() {
  return HtmlService.createTemplateFromFile('HTMLUI').evaluate()
  .setSandboxMode(HtmlService.SandboxMode.NATIVE);
}

Here is HTML

HTMLUI.html

<script type="text/javascript"></script>
<script>
<?
  var sheet   = SpreadsheetApp.openById("0Avt7ejriwlxudGZfV2xJUGJZLXktQ2RhQU1uRUgtaXc").getSheetByName("MRF Tab");
  var lastRow = sheet.getLastRow();  
  var myRange = sheet.getRange("C3:C"+lastRow); 
  var data    = myRange.getValues();
?>
</script>
<select>
<? for (var i = 0; i < sourcedata.length; ++i) { ?>
<option><?!= sourcedata[i] ?></option>
<? } ?>
</select>

I had this code in one of my project (and a lot more code) which basically captures information form the sheet and add it to the options (dropdown) in select, but when trying this same code in new project this isnt working, any ideas what am I missing.

At present the result displayed is a dropdown box with <?!=sourcedata[i]?>

How can I correct this. Any help please.

EDIT:---

Please have a look @ comment no 3 for link to a spreadsheet and some workaround with it...


Solution

  • The results you describe are the result of nested templated HTML - it's clear that the evaluator isn't designed to handle it, so the unevaluated scriptlets are being shown as text.

    You're using templated HTML in test.html to include templated HTML from HTMLUI.html, and the include() function tries to treat the content of HTMLUI.html as regular (non-templated) HTML source.

    One way around this would be to use a version of include() specifically for templated html. Put this in your gs file:

    function includeTemplate(filename) {
        return HtmlService.createTemplateFromFile(filename).evaluate()
          .setSandboxMode(HtmlService.SandboxMode.NATIVE)
          .getContent();
    }
    

    Your test.html then becomes:

    <?!= includeTemplate('HTMLUI'); ?>
    

    This will accomplish what you're trying in your example. To do so, though, you're losing some of the capabilities of templated html, as you will not have the opportunity to push variables to the template.