提问人:Tom Sauder 提问时间:11/18/2023 最后编辑:TheMasterTom Sauder 更新时间:11/22/2023 访问量:41
如何使用 AppScript 将文档中的标签替换为另一个文档的内容?
How do I use AppScript to replace a tag in a document with the contents of another document?
问:
我有一个应用程序,我正在根据某些标准从一堆模板文档中构建文档。这很好用,除了在我的许多模板中都有相同的文本块,并且当我必须在一个模板中更改此文本时,我最终不得不在多个模板中更改相同的文本。我的解决方案是用标签标记模板中的这些部分,当遇到标签时,我会将标签替换为正确文档的内容。
我的标签都以“@@”开头。例如,当遇到标签“@@HELPFUL_LINKS”时,我想将该标签替换为名称为“@@HELPFUL_LINKS”的文件的内容。
这是我执行此操作的代码:
// Find any '@@' tags and replace them with the correct block of text
var blkTag = null;
while(blkTag = cell.findText(TAG_INDICATING_INSERTION), blkTag)
{
var startTag = blkTag.getStartOffset();
var endTag = blkTag.getElement();
var tagText = blkTag.getElement().asText();
console.log(`Tag found is ${tagText}`);
var newTextFileId = getFileByName_(PROJECT_FOLDER_NAME, tagText);
if(newTextFileId != null)
{
var tagDoc = DocumentApp.openById(newTextFileId);
var tagContentText = tagDoc.getBody().getText();
tagText.deleteText(startTag, endTag);
tagText.insertText(start, tagContentText);
}
}
当遇到“@@HELPFUL_LINKS”时,我本以为tagText是文本“@@HELPFUL_LINKS”,但它是“Text”。
答:
0赞
Tom Sauder
11/22/2023
#1
好吧,我自己想通了。我缺少的是,即使我设置了变量 tagText = blkTag.getElement().asText(),为了实际查看文本,我也必须使用 tagText.getText()。这并不直观。
这是我的最后一个代码,它找到标签并将其替换为与标签同名的文件的内容。
function findAndReplaceTags(tCell)
{
// Find any '@@' tags and replace them with the correct block of text from a file
var blkTag = null;
while(blkTag = tCell.findText("@@.*$", blkTag)) // regex search
{
var startTag = blkTag.getStartOffset();
var endTag = blkTag.getEndOffsetInclusive();
var tagText = blkTag.getElement().asText();
// This goofy looking code is required to find the location in the
// cell to insert the new information.
var rngEl = blkTag.getElement();
var parent = rngEl.getParent()
var chIdx = parent.getParent().getChildIndex(parent);
var newTextFileId = getFileByName_(PROJECT_FOLDER_NAME, tagText.getText());
if(newTextFileId != null)
{
var tagDoc = DocumentApp.openById(newTextFileId);
var insertPars = tagDoc.getBody().getParagraphs();
tagText.deleteText(startTag, endTag);
insertPars.forEach(par => {
tCell.insertParagraph(chIdx, par.copy());
chIdx++; // as each paragraph is added, the child index has to increase
});
}
}
}
评论
My tags all start with '@@'. For example, when the tag '@@HELPFUL_LINKS' is encountered, I want to replace that tag with the contents of a file with the name '@@HELPFUL_LINKS'.
@@HELPFUL_LINKS
For example, when the tag '@@HELPFUL_LINKS' is encountered, I want to replace that tag with the contents of a file with the name '@@HELPFUL_LINKS'.