Search code examples
google-apps-scriptgoogle-sheetsgoogle-slides-api

Creating new copies of slides with data from google sheets without loosing original template


I have made a script that replaces placeholder text in google slides with information from google sheet. However once I have run the script once my slides template is overwritten with the injected information.

How to I preserve my original template while generating new copies of my slides?

I use the "SpreadsheetApp.openById" to get the spreadsheet, and I am also able to save a copy of the new file using "DriveApp.getFileById" and "makeCopy()". However my original template is still overwritten and all my placeholder tags {{tag}} are lost.

I use this function for replacing elements in the google slide:

values.forEach(function(row){
var templatevariable= row[0];
var templatevalue= row[1]
Presentation.replaceAllText(templatevariable,templatevalue);  
})

Solution

  • Create a duplicate and then work on the duplicate.

    
    var copiedFile = createCopyUsingDriveApp()
    
    values.forEach(function(row){
      var templatevariable= row[0];
      var templatevalue= row[1]
      copiedField.replaceAllText(templatevariable,templatevalue);  
    })
    
    
    function createCopyUsingDriveApp() {
     // The Id of the presentation to copy
     var templateId = "<SLIDES_ID>";
    
     // Create a copy of the presentation using DriveApp
     var template = DriveApp.getFileById(templateId);
     var fileName = template.getName();
     var copy = template.makeCopy();
     return copy.setName("Copy of " + fileName);
    }