Search code examples
google-apps-scriptgoogle-apps

Google Script Pass variable to templated HTMLService


I have a script which I have published as a web app. I wanted to change a default setting based on the URL used to run the web app. I am already opening one of two forms, but on one form, I want to have a radio button selected based on a second passed parameter. In the server side gs file I have:

function doGet(passed) {

  switch(passed.parameter.form) {
    case 'single':
        var result = HtmlService.createTemplateFromFile('Single').evaluate();
        result.setHeight(550);
        result.setWidth(565);
        break;
    case 'grid':
    default:
        var result=HtmlService.createTemplateFromFile('GridView').evaluate();
        result.setHeight(550);
        result.setWidth(1285);
      }

  return result;
    }

On Google's HTML Service: Templated HTML page there is a section Pushing variables to templates which seems to be what I want but I can't get it to work.

in my Single.html file I have:

      <body>
         <? if (data === "Ex") { ?> Existing <? } else { ?> New <? } ?>    
       ... </body>

The html portion above is overly simplified and getting this to work will get me to my ends, which is a much larger page with input areas, etc.

In an attempt to get "Existing" to display in the resulting page, I have changed the above code to:

function doGet(passed) {

  switch(passed.parameter.form) {
    case 'single':
        var result = HtmlService.createTemplateFromFile('Single');
        result.setHeight(550);
        result.setWidth(565);
        result.data = 'Ex';
        return result.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
        break;
    case 'grid':
    default:
        var result=HtmlService.createTemplateFromFile('GridView').evaluate();
        result.setHeight(550);
        result.setWidth(1285);

        return result;
      }

    }

and get errors

TypeError: Cannot find function setHeight in object HtmlTemplate. (line 131, file "Code")

Even if I remove the setHeight and setWidth resulting in just have the data as shown on the above referenced page I get errors.

Has anyone passed a variable to a page like this?


Solution

  • Looks like the method calls are just in the wrong order. The result.data = 'Ex'; should be before the .evaluate(), but the .setHeight() and .setWidth() must be applied afterwards. Modifying your last example slightly:

    case 'single':
            var result = HtmlService.createTemplateFromFile('Single');
            result.data = 'Ex';
    
            return result.evaluate()
                         .setHeight(550)
                         .setWidth(565)
                         .setSandboxMode(HtmlService.SandboxMode.IFRAME);
            break;
    

    I tracked down the basic error to a missed } after your if statement in your HTML file. The code should look like:

    <? if (data === "Ex") { ?> Existing <? } else { ?> New <? } ?>