Use variable value from .gs file in custom HTML sidebar

喜欢而已 提交于 2019-12-06 23:41:06

Getting data from a spreadsheet on loading a sidebar

Don't forget to select the row first before displaying the sidebar.

code.gs

function openThisSideBar()
{
  var html = HtmlService.createHtmlOutputFromFile('hotel').setTitle('MySideBar');
  SpreadsheetApp.getUi().showSidebar(html);
}

function getHotel()
{
  var s=SpreadsheetApp.getActive().getSheetByName("Contract Registry Document");
  var row=s.getActiveCell().getRow();
  var n=Utilities.formatString('Your Hotel is named: %s',s.getRange(row, 9).getValue());
  return n;
}

function onOpen()
{
  SpreadsheetApp.getUi().createMenu('MyTools')
    .addItem('Open Sidebar', 'openThisSideBar')
    .addToUi();
}

hotel.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    $(function()
    {
       google.script.run
           .withSuccessHandler(updateHotel)
           .getHotel();
    });
    function updateHotel(name)
    {
       document.getElementById('hotel').innerHTML=name;
    }
    console.log('MyCode');
    </script>
  </head>
  <body>
   <div id="hotel"></div> 
  </body>
</html>

You can add your refresh like this:

<script>
function refresh()
    {
       google.script.run
          .withSuccessHandler(updateHotel)
          .getHotel();
    }
</script>

And the new html:

<input type="button" value="Refresh" onClick="refresh();" />

That way you needn't refresh the entire page but just the div.

Use Scriptlets with createTemplateFromFile() and evaluate(). Then use the printing scriptlets in the html file and set their value in your openSidebar()

function openSidebar() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var s=ss.getSheetByName("Contract Registry Document");
  var row=s.getActiveCell().getRow();
  var column=9;
  var hotelName = s.getRange(row, column).getValue();

  // get the html template after retrieving the values
  var html_template = HtmlService.createTemplateFromFile('index');

  // set the value for the index.html `hotel` placeholder/scriptlet
  html_template.hotel = hotelName;

  // evaluate the template
  var sidebar_html = html_template.evaluate();

  SpreadsheetApp.getUi().showSidebar(sidebar_html);

  Logger.log(hotelName);
}

index.html

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