【问题标题】:Google HTML Service - Evaluate Template and Keep CommentsGoogle HTML 服务 - 评估模板并保留评论
【发布时间】:2021-05-15 17:22:14
【问题描述】:

我正在使用 Google 的 HTML 服务来评估 HTML 模板,然后通过 Google 的 Mail App 服务将它创建的 HTML 作为电子邮件发送。我有以下代码为 Microsoft Office 客户端呈现不同的电子邮件:

<!--[if mso]><v:roundrect...v:roundrect><![end if]-->
<!--[if !mso]><td align='center'...</td><![endif]-->

我的问题是 HTML 服务将上述代码评估为注释掉,并且传递给邮件应用程序的 HTML 中不再包含这些代码行。

我一直在苦苦思索如何让 Google 的 HTML 服务不将这些视为 cmets。有什么想法吗?

谢谢!

【问题讨论】:

    标签: html email google-apps-script


    【解决方案1】:

    有一种迂回的方法可以在模板评估后保留HTML cmets,但它也有其自身的问题。

    您首先将模板中的 cmets 括在 CDATA 标记中。请参见下面的示例:

    <!DOCTYPE html>
    <html>
      <head>
        <base target="_top">
      </head>
      <body>
        <![CDATA[<!-- This is a comment -->]]>
        <p>GET - Gmail Push Notification Endpoint</p>
      </body>
    </html>
    

    评估后,您将得到以下结果:

    <!DOCTYPE html>
    <html>
      <head>
        <base target="_top">
      </head>
      <body>
        &lt;!-- This is a comment --&gt;
        <p>GET - Gmail Push Notification Endpoint</p>
      </body>
    </html>
    

    请注意,某些字符(&lt;&gt;)被编码为 html 实体,因此您需要以某种方式将它们转换回来。不幸的是,Javascript 没有本地方式来做到这一点,因此您要么必须编写自己的脚本来替换它们,要么使用现有的库。我做后者并利用he library。您可以在您的 Apps 脚本项目中创建一个脚本文件,并将该代码作为依赖项放入其中,或者将其放入自己的项目中并将其部署为专用的 Apps 脚本库。

    现在您可以将它们组合在一起,如下所示:

    // create template
    let template = HtmlService
        .createTemplateFromFile('template_with_comments_wrapped_in_CDATA_tags');
    
    // add properties to template for evaluation
    template.props = {...};
    
    // get evaluated content as string
    let evaluated = template
        .evaluate()
        .getContent();
    
    // decode html entities
    let decoded = he.decode(evaluated);
    
    // return decoded as HtmlOutput
    return HtmlService.createHtmlOutput().setContent(decoded); 
    

    你去吧。

    在模板中使用CDATA 标签包含内容有很多应用,它甚至允许您使用非 HTML 内容作为模板,因此您可以使用此技术为各种内容创建模板(JSON、RFC822 , 等等。)。在您的工具库中拥有一个很好的技巧。

    【讨论】:

    • 谢谢!我打算看看我是否可以使用 XML 服务来获取文档、插入注释并返回给 HTML 服务。我去了科斯托,然后又回到了这个美妙的解决方案!不仅是解决此问题的好方法,而且正如您所指出的,它具有许多潜在的用例。对于任何利用 App Script 的人来说,这绝对是技巧包里的东西。
    【解决方案2】:

    发生这种情况的原因是因为它们确实是 HTML cmets

    查看此reference 了解如何在 HTML 中发表评论。

    要解决您的问题,只需注释掉您的代码行(即删除 &lt;!----&gt;):

    [if mso]><v:roundrect...v:roundrect><![end if]
    [if !mso]><td align='center'...</td><![end if]
    

    【讨论】:

    猜你喜欢
    • 2021-09-29
    • 2021-07-23
    • 2015-06-12
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 2015-09-12
    • 2012-09-11
    • 1970-01-01
    相关资源
    最近更新 更多