Ben
Ben

Reputation: 31

Google App Script add new list items when replacing text in Docs

I've created a script which, when a form is submitted, is triggered to create a document and replace several tags with the information from the answers.

As part of this, I create a variable which stores several answers with line breaks between them, e.g.:

if (marketingConditions.includes("Option 1")) {
  marketingConditionsReplacement = marketingConditionsReplacement + '\n' + "List item 1";
}
if (marketingConditions.includes("Option 2")) {
  marketingConditionsReplacement = marketingConditionsReplacement + '\n' + "List item 2";
}
if (marketingConditions.includes("Option 3")) {
  marketingConditionsReplacement = marketingConditionsReplacement + '\n' + " List item 3";
}

I then have a bullet point in my document which has a reference and is replaced with:

body.replaceText("{{MarketingConditions}}", marketingConditionsReplacement);

However, the new line (as expected) does not append each of these string elements as new list items.

I want it to create this

if all of the conditions are true, for example.

I'm wondering if it's better to do this with an array instead, where each of them is appended as a separate item, but I'm not sure how I could use 'appendListItem' with this.

Any suggestions would be very much appreciated as I'm very new to App Scripts!

Upvotes: 2

Views: 1641

Answers (1)

Yuri Khristich
Yuri Khristich

Reputation: 14537

I'd prefer to use an array indeed.

Suppose you have the doc template like this:

enter image description here

You can replace the list by elements of your array this way:

function main() {
  var list_items = ['List item 1', 'List item 2', 'List item 3']; // the array
  
  var body = DocumentApp.getActiveDocument().getBody();

  var list = body.getListItems()[0];      // get the template list
  var atts = list.getAttributes();        // get the list attributes
  var indent = list.getIndentFirstLine(); // get the list indent

  list.setText(list_items[0]);            // replace 1st line of the list
  
  var index = body.getChildIndex(list);   // get number of paragraph that contains the list


  // append elements of the array to the list

  for (var i=1; i<list_items.length; i++) {
    var new_list_item = body.insertListItem(index+i, list_items[i]);
    new_list_item.setAttributes(atts);
    new_list_item.setIndentFirstLine(indent);
  }
}

Output will look like this:

enter image description here

References:

https://developers.google.com/apps-script/reference/document/list-item

https://developers.google.com/apps-script/reference/document/glyph-type

Upvotes: 2

Related Questions