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

如何用Google Apps Script输出HTML源代码?

如何在Apps Script Web应用中直接展示HTML源代码
  • 核心思路:先获取模板渲染后的完整HTML字符串,转义特殊字符后用<pre>标签包裹输出,就能直接展示源代码而非渲染后的页面。

  • 修改后的doGet函数示例:

function doGet(e) {
  // 渲染模板并获取生成的HTML字符串
  const renderedHtml = HtmlService.createTemplateFromFile("html_template").evaluate().getContent();
  // 批量转义HTML特殊字符
  const escapedHtml = renderedHtml.replace(/&/g, '&amp;')
                                 .replace(/</g, '&lt;')
                                 .replace(/>/g, '&gt;')
                                 .replace(/"/g, '&quot;');
  // 用带样式的<pre>标签包裹,保留格式并提升可读性
  return HtmlService.createHtmlOutput(`
    <pre style="background-color: #f8f9fa; padding: 1.2rem; border-radius: 6px; overflow-x: auto; font-family: monospace;">
      ${escapedHtml}
    </pre>
  `);
}
  • 关键说明:
    1. getContent()方法会返回模板渲染后的纯HTML文本,而非渲染后的页面对象;
    2. 批量替换特殊字符是为了避免浏览器解析HTML标签,确保所有代码以文本形式展示;
    3. <pre>标签会保留原始的换行和缩进,配合样式可以让代码展示更清晰,方便直接复制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 07:14:53