【问题标题】:Google App Script add new list items when replacing text in DocsGoogle App Script在替换文档中的文本时添加新的列表项
【发布时间】:2021-08-12 11:16:06
【问题描述】:

我创建了一个脚本,当提交表单时,它会触发创建文档并用答案中的信息替换几个标签。

作为其中的一部分,我创建了一个变量来存储多个答案,它们之间有换行符,例如:

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";
}

然后我的文档中有一个项目符号点,它有一个参考并替换为:

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

但是,新行(如预期的那样)不会将这些字符串元素中的每一个都附加为新的列表项。

我希望它创建这个

  • 列表项 1
  • 列表项 2
  • 列表项 3

例如,如果所有条件都为真。

我想知道是否最好使用数组来代替,其中每个都作为单独的项目附加,但我不确定如何使用“appendListItem”。

非常感谢任何建议,因为我是 App Scripts 的新手!

【问题讨论】:

    标签: google-apps-script google-docs


    【解决方案1】:

    我确实更喜欢使用数组。

    假设你有这样的文档模板:

    您可以通过这种方式将列表替换为数组的元素:

    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);
      }
    }
    

    输出将如下所示:

    参考资料:

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

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

    【讨论】:

    • 如果“模板列表”是文档中多个单独列表之一中的最后一个列表项怎么办。有什么方法可以找到开始从数组中添加列表项的特定位置?
    • var all_lists = body.getListItems() 获取文档中的所有列表。 var list = body.getListItems()[all_lists.length-1] 为您提供文档中的最后一个列表。实际上,您可以在模板列表中放入一些独特的短语,并在将其放入文档时找到该列表。这是我的示例,您如何找到包含单词“Derek”stackoverflow.com/a/68764572/14265469 的表格行
    • 我在这里重新表述了这个问题:stackoverflow.com/questions/68774323/… - 我认为我在这里解释得不是很好,但我很感谢你到目前为止的时间!
    猜你喜欢
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多