Web App Development with Google Apps Script/Templated html

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Putting variables into html pages[edit | edit source]

As noted in the Hello World chapter, you can have a basis of an html page by creating one and using it as a template. Normally you'd want to tailor that page with information from the server (ie usually one of your Google Sheets). You can use the various templating tools to do that.

You send a variable to the template with t.coolvariable="whatever" and you put it in the html document with <?= coolvariable ?>.

doGet code[edit | edit source]

from "code.gs":

function doGet() {
   var t = HtmlService.createTemplateFromFile("main");
   t.coolvariable = "hi there";
   return t.evaluate();
   }

html code[edit | edit source]

From "main.html":

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <?= coolvariable ?>
  </body>
</html>

Web result[edit | edit source]

hi there

More complex variables[edit | edit source]

If you want to send something more complex than a string, there are a few options:

  • <?!= somevariable ?> will print things with special characters in it. This is useful, for example, for strings that contain html tags in them.
  • var pagevariable = <?!= JSON.stringify(somevariable) ?>; inside a <script> tag on the html page will then let the local javascript deal with it as a global variable.
  • If you have a bunch of variables that you want to have as global variables in the html document:
    • t.globals={"var1":var1, "var2":var2}; in the code.gs doc
    • var globals = <?!= JSON.stringify(globals) ?>;
      Object.keys(globals).forEach(key=>window[key]=globals[key]);
      
    • this works because the window object is the global so-called "namespace" for the html document. That just means it's where global variables sit.

Passing functions[edit | edit source]

The Google Apps Script editor doesn't work very well when checking for syntax errors in javascript code that's embedded in an html file. Here's a trick to let you write javascript functions in the server code spaces (which lets them be syntax checked) and then pass them to the client. The trick is to use function expressions.

In the server side you'd do this:

function doGet() {
  var t=HtmlService.createTemplateFromFile("main");
  t.funcs=[a,b,temp];
  t.funcnames=t.funcs.map(f=>f.name);
  return t.evaluate();
}

var a=(c,d)=>c+d;
var b=(e,f)=>e*f;
var temp=(a,b,c)=>{
                    var d=a+b;
                    var e=b*c;
                    return d+e;
                   }

and in the client html file you'd do this:

var funcnames=<?!= JSON.stringify(funcnames) ?>;
var funcs=[<?!= funcs ?>];
funcnames.forEach((fn,i)=>window[fn]=funcs[i]);