如何向HTML模板侧边栏传递值?Google Apps Script问题求助
Got it, let's sort out that missing email display in your sidebar. The root issue is that you're fetching the user's email server-side in openLeadership() but never passing that variable to your HTML template—right now the template has no access to the sessionEmail value you're trying to render.
Step 1: Update the openLeadership.gs File
You need to use a template file instead of a static HTML file, so you can inject server-side variables into the client-side HTML. Here's the revised code:
function openLeadership() { // Fetch the user's email (you already had this part) var leaderEmail = Session.getActiveUser().getEmail(); // Create a template from your Sidebar.html file var htmlTemplate = HtmlService.createTemplateFromFile('Sidebar'); // Pass the email variable to the template (matches the variable name in your HTML) htmlTemplate.sessionEmail = leaderEmail; // Evaluate the template to inject variables, then configure the sidebar var html = htmlTemplate.evaluate() .setSandboxMode(HtmlService.SandboxMode.IFRAME) .setTitle('Leadership') .setWidth(100) .setHeight(200); SpreadsheetApp.getUi().showSidebar(html); }
What Changed?
- Replaced
createHtmlOutputFromFile()withcreateTemplateFromFile(): This tells Apps Script to treat your HTML file as a template that can accept server-side variables. - Added
htmlTemplate.sessionEmail = leaderEmail: This binds the server-sideleaderEmailvalue to thesessionEmailvariable your HTML template is trying to use. - Used
evaluate(): Processes the template to replace<?= sessionEmail ?>with the actual email value before rendering the sidebar.
Step 2: Verify Your Sidebar.html Template
Your existing HTML code for displaying the email is already correct—no changes needed here:
<p> <b>Logged in as <?= sessionEmail ?></b> </p>
Why This Works
createHtmlOutputFromFile()loads HTML as static text, so it ignores the<?= ?>template scriptlets.createTemplateFromFile()+evaluate()parses those scriptlets and injects the server-side variable values directly into the HTML before sending it to the sidebar.
Extra Notes
- You mentioned you confirmed
Session.getActiveUser().getEmail()works in your Google Workspace environment, so we don't need to handle any permission edge cases here. - Your
showUpdatesMenu()function is fine as-is—it's just creating the menu, and itssessionEmailvariable is unrelated to the sidebar's display.
内容的提问来源于stack exchange,提问作者swolfe2
相关产品推荐
相关产品推荐

