Skip to content

Instantly share code, notes, and snippets.

@andrewroberts
Created September 17, 2017 10:02
Show Gist options
  • Save andrewroberts/63da33a83a4fe5a6365015e4f39c1a42 to your computer and use it in GitHub Desktop.
Save andrewroberts/63da33a83a4fe5a6365015e4f39c1a42 to your computer and use it in GitHub Desktop.
Google Apps Script function to replace placeholder values in an HTML template (from a draft GMail for example)
/**
* For each placeholder - "{{[placeholder]}}", strip out any HTML and replace
* it with the appropriate key value. An example use of this could be using the
* HTML from a draft GMail as a template.
*
* E.g. If the obect were:
*
* {PlaceHolder1: newValue}
*
* In the template "{{PlaceHolder1}}" would be replaced with "newValue" even
* if there were some HTML (<...>) inside the brackets.
*
* https://github.com/shantanu543/bulk-mail/blob/master/bulkmail.gs
*
* @param {String} template HTML or plain text
* @param {Object} rowObject replacement values: {[placeholder]: [new value]}
*
* @return {String} completed template
*/
function fillInTemplate(template, rowObject) {
Logger.log('template: ' + template)
Logger.log('rowObject: ' + JSON.stringify(rowObject))
var completed = template.replace(/{{.*?}}/g, function(nextMatch) {
Logger.log('nextMatch: ' + nextMatch)
// Remove any HTML inside the placeholder
var placeholderValue = nextMatch.replace(/<.*?>/g, '')
Logger.log('placeholderValue (HTML stripped): ' + placeholderValue)
// Strip the placeholder identifier
placeholderValue = placeholderValue.substring(2, placeholderValue.length - 2)
Logger.log('placeholderValue (ids removed): ' + placeholderValue)
var nextValue = rowObject[placeholderValue]
Logger.log('nextValue: ' + nextValue)
return nextValue
})
return completed
} // fillInTemplate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment