Search code examples
templatesgoogle-apps-scriptdocumentnumbered-list

Numbered lists continues when Apps Script appends template-content into document


I have an Apps Script that copies the content of an template-file to the end of a document. It works with one minor annoyance: the numbered list continues from one copy to the next.

I have many different templates that users can append to the end of the document. Each template is stored in its own Document.

    function addSub(template_id){
      var mainBody = DocumentApp.getActiveDocument().getBody();
      var tempBody = DocumentApp.openById(template_id).getBody();
      for(var i = 0;i<tempBody .getNumChildren();i++){
        var element = tempBody .getChild(i);
        if(element.getType() == DocumentApp.ElementType.TABLE)
          mainBody.appendTable(element.copy());
        else if(element.getType() == DocumentApp.ElementType.PARAGRAPH)
          mainBody.appendParagraph(element.copy());
        else if(element.getType() == DocumentApp.ElementType.LIST_ITEM)
          mainBody.appendListItem(element.copy());
        else if(element.getType() == DocumentApp.ElementType.PAGE_BREAK)
          mainBody.appendPageBreak(element.copy());
      }
    }

It could look like this: ( I want the list to reset for each new copy of the template)

table with name of this template

some raw text

  1. List item1
  2. List item2

table with name of this template

some raw text

  1. List item1
  2. List item2

Solution

  • After Richard Gantz solved it, It was corrected by this code:

    var listItemDictionary = {};//top
    

    ...

    else if(element.getType() == DocumentApp.ElementType.LIST_ITEM){
      var listCopy = element.copy().asListItem()
      var lcID = listCopy.getListId();
      if (listItemDictionary[lcID] == null){
        var tempLI = mainBody.appendListItem("temp")
        listItemDictionary[lcID] = tempLI;
      }
      Logger.log(lcID)
      mainBody.insertListItem(childIndex+j, listCopy.setListId(listItemDictionary[lcID]));
    }
    

    ...

    if(listItemDictionary){//bottom
      mainBody.appendParagraph("");
      for(var key in listItemDictionary){
        listItemDictionary[key].clear().removeFromParent()
      }
    }