Created
October 18, 2016 23:25
-
-
Save danilat/188665d8273aa2bbd313d783e514666b to your computer and use it in GitHub Desktop.
A template parser for google docs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// (Get ids from the URL) | |
var SOURCE_TEMPLATE = "doc-id"; | |
var VARIABLES = "spreadsheet-id"; | |
var TARGET_FOLDER = "folder-id"; | |
/** | |
* Get variables with key/value format | |
*/ | |
function getVariables(sheet) { | |
var dataRange = sheet.getRange("A1:B99"); | |
var data = dataRange.getValues(); | |
var variables = {}; | |
var variablesLength = data.length; | |
for(var i=0; i< variablesLength; i++) { | |
var row = data[i]; | |
var key = row[0]; | |
var value = row[1]; | |
if(!key) { | |
break; | |
} | |
variables[key] = value; | |
} | |
return variables; | |
} | |
/** | |
* Duplicates a Google Apps doc, returns a new document with a given name from the orignal | |
*/ | |
function createDuplicateDocument(templateId, name) { | |
var template = DriveApp.getFileById(templateId); | |
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER); | |
var newFile = template.makeCopy(name, targetFolder); | |
return DocumentApp.openById(newFile.getId()); | |
} | |
/** | |
* Search a paragraph in the document and replaces it with the generated text | |
*/ | |
function replaceParagraph(doc, keyword, value) { | |
var ps = doc.getParagraphs(); | |
var variable_key = "{{"+keyword+"}}" | |
for(var i=0; i<ps.length; i++) { | |
var p = ps[i]; | |
var text = p.getText(); | |
if(text.indexOf(variable_key) >= 0) { | |
var foo = text.indexOf(variable_key); | |
var newText = text.split(variable_key).join(value); | |
p.setText(newText); | |
} | |
} | |
} | |
/** | |
* Script entry point | |
*/ | |
function parse() { | |
var data = SpreadsheetApp.openById(VARIABLES); | |
// Fetch variable names | |
var sheet = data.getSheets()[0]; | |
var variables = getVariables(sheet); | |
Logger.log("Existing variables:" + variables); | |
var customerName = variables.name; | |
var target = createDuplicateDocument(SOURCE_TEMPLATE, customerName + "_report"); | |
Logger.log("Created new document:" + target.getId()); | |
for (var key in variables) { | |
var value = variables[key]; | |
replaceParagraph(target, key, value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment