Google Apps Script allows you to serve dynamic HTML content directly from your scripts. This is primarily achieved through the HtmlService which enables you to create custom user interfaces for your applications. Think of it as building your own web pages that are hosted and served by Google, powered by your Apps Script code.
The core of serving HTML involves creating an HTML file within your Apps Script project and then using a script function to serve that file. You can create HTML files directly in the Apps Script editor by going to 'File' > 'New' > 'HTML file'. These files are then accessible via their name in your script.
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}In the code above, doGet() is a special function that runs when a web app is accessed via its URL. HtmlService.createHtmlOutputFromFile('Index') tells Apps Script to find an HTML file named 'Index.html' in your project and render it as the response to the web app request. This is the most straightforward way to serve a static HTML file.
Beyond static HTML, HtmlService also allows you to dynamically generate HTML content as a string. This is useful when you need to populate your HTML with data retrieved from other Google services or calculated within your script. For this, you'll use HtmlService.createHtmlOutput(htmlString).
function doGet() {
var htmlBody = "<html><body><h1>Hello from Apps Script!</h1></body></html>";
return HtmlService.createHtmlOutput(htmlBody);
}For more advanced scenarios, such as creating templated HTML where you want to inject data into a pre-defined HTML structure, HtmlService provides createTemplateFromFile(filename). This method creates an HtmlTemplate object, which you can then evaluate and serve. Templated HTML uses a special syntax to embed Apps Script code directly within your HTML.
// In your HTML file (e.g., Template.html):
<html>
<body>
<h1>Hello, <?= name ?>!</h1>
<p>Your favorite color is: <?= favoriteColor ?></p>
</body>
</html>
// In your Apps Script (.gs file):
function doGet() {
var template = HtmlService.createTemplateFromFile('Template');
template.name = 'Alice';
template.favoriteColor = 'blue';
return template.evaluate();
}