Getting an htmlservice template from a library

If you use HTMLservice templates, you may want to centralize useful ones and use them in multiple projects, just like you can with library scripts.
All you need to make this work is a library with your template file and a one line function in your library. Here's a snippet from Displaying analytics data on site pages, where I have my template in a library file, as opposed to the project I'm working on. 

In my library, I have this function

function getInstrumentationCode () {
  return HtmlService
    .createTemplateFromFile('instrumentationTemplate')
    .evaluate()
    .getContent();
}

and an html template called 'instrumentationTemplate'

Back in my main project I call it like this

    // create the page
    return HtmlService
      .createTemplate(cSiteStats.getInstrumentationCode())
      .evaluate();

Job done. Now I can use the same template across multiple templates. 

See Google Apps Scripts snippets for more like this

For help and more information join our forumfollow the blogfollow me on twitter

You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.




Comments