You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向HTML模板侧边栏传递值?Google Apps Script问题求助

Fix: Sidebar Not Displaying User Email in 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() with createTemplateFromFile(): 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-side leaderEmail value to the sessionEmail variable 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 its sessionEmail variable is unrelated to the sidebar's display.

内容的提问来源于stack exchange,提问作者swolfe2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:02:35