How to access template variables in the script section of my HTML file in Google Apps Script?

喜夏-厌秋 提交于 2020-03-25 19:13:10

问题


I need to access templated variables in the script section of my HTML file. Specifically, I need to use content.price.

I can access content.price just fine in the templated section of the body of my HTML.

This behaves as expected.
<div class="container">
  Price: $<?= content.price ?></td>
  <div id="paypal-button-container"></div>
</div>

But in the script section, trying to access content.price seems to be throwing an exception.

This causes the buttons to fail to render. (It fails silently.)
amount: {
  value: content.price //  '0.01' // Using content.price throws an error
}

What am I doing wrong?

Code.gs
var template = HtmlService.createTemplateFromFile(HTML_FILENAME);
template.content = values;
var htmlOutput = template.evaluate();
index.html
<!DOCTYPE html>
  <!-- source: https://developer.paypal.com/docs/checkout/integrate/ -->
  <html>
    <body>
      <div class="container">
        Price: $<?= content.price ?></td>
        <div id="paypal-button-container"></div>
      </div>
      <script
        src="https://www.paypal.com/sdk/js?client-id=SB_CLIENT_ID">
      </script> 
      <script>
        // This function displays Smart Payment Buttons on your web page.
        paypal.Buttons({
          createOrder: function(data, actions) {
            // This function sets up the details of the transaction, including the amount and line item details.
            return actions.order.create({
              purchase_units: [{
                amount: {
                  value: content.price //  '0.01' // Using content.price throws an error
                }
              }]
            });
          },
        }).render('#paypal-button-container');
      </script>
    </body>
  </html>

回答1:


In script section also you'll need to use template tags.

Something like these :

amount: {
  value: <?!= content.price ?>
}


来源:https://stackoverflow.com/questions/60073188/how-to-access-template-variables-in-the-script-section-of-my-html-file-in-google

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!