One of the most powerful features of Google Apps Script's HTML Service is its ability to dynamically generate HTML content. This means your web apps can go beyond static displays and present information that changes based on user input, data from your spreadsheets, or other real-time factors. The primary mechanism for achieving this is through scriptlets.
Scriptlets are special embedded code snippets within your HTML templates that allow you to execute Google Apps Script code directly within the browser's rendering process. This enables you to inject dynamic values, control the flow of your HTML, and even perform server-side operations before the HTML is sent to the user.
There are two main types of scriptlets you'll encounter:
- Evaluation Scriptlets (
<?= ... ?>): These are used to directly embed the result of a scriptlet expression into the HTML. Whatever is returned by the code within the<?= ... ?>tags will be rendered as text in your HTML. This is perfect for displaying variable values or the results of simple function calls.
<html>
<body>
<h1>Welcome, <?= user.getName() ?>!</h1>
<p>Your email is: <?= user.getEmail() ?></p>
</body>
</html>In the above example, user.getName() and user.getEmail() would be calls to functions within your Apps Script code, and their returned values would be inserted directly into the HTML.
- Execution Scriptlets (
<% ... %>): These scriptlets are used for executing code that doesn't necessarily produce a direct output to be displayed, but rather controls the logic of your template. This includes loops, conditional statements, and function definitions. The code within<% ... %>is executed on the server before the HTML is sent to the client.
<html>
<body>
<h2>Your Tasks:</h2>
<ul>
<% for (var i = 0; i < tasks.length; i++) { %>
<li><%= tasks[i] %></li>
<% } %>
</ul>
</body>
</html>