What is the purpose of HTML evaluation in Apps Script?

Viewed 151

I am currently learning Apps Script fundamentals. I've encounter a method:

evaluate()

e.g.

  const htmlServ = HtmlService.createTemplateFromFile("main");
  const html = htmlServ.evaluate(); // 

Within the reference it says:

It evaluates template and returns an HtmlOutput object.

My question: Does evaluate() has anything to do with security internally in Apps Script? Any relationship with HTML entities and its escaping? I want to clear this out.

Thanks.

1 Answers

evaluate() just injects data to your HTML templates. AFAIK it has nothing to do with the security.

The most common use case of this mechanism is when you have (nicely styled :)) HTML template that you want to have dynamic data. For example you have daily report that you want to display on a HTML page or send by email that has HTML body. But each day your Daily Total Revenue is different. You would do something like this:

<!-- Inside index.html file -->
<html>
  <div class=my-class">
    <p>Daily Total Revenue is: <?= dailyTotalRevenueVar ?>.</p>
  </div>
</html>

// Inside Code.gs file
const template = HtmlService.createTemplateFromFile("index");
template.dailyTotalRevenueVar = 1000000; // Add a property to the template
const htmlOutput = template.evaluate(); // Replace var in HTML with actual value 1000000
Logger.log(htmlOutput.getContent()); // or return as a result in doGet()

You have many more options besides the simple value replacing, you can skip the entire HTML block if array has zero length, you can make a for loop to fill the select options...

Take a look at this page (toggle between .gs and .html view in code examples) https://developers.google.com/apps-script/guides/html/templates

For more info about doGet and publishing GAS project as a web application visit this page: https://developers.google.com/apps-script/guides/web

Related