I have an application where I am building a document from a bunch of template documents based on certain criteria. This works fine except that there are blocks of text that are identical in many of my templates, and when I have to change this text in one template, I end up having to change the same text in multiple templates. My solution is to mark these sections in the template with a tag and when the tag is encountered, I then will replace the tag with the contents of the correct document.
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'.
Here is my code for doing this:
// 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);
}
}
When '@@HELPFUL_LINKS' is encountered, I was expecting tagText to be the text '@@HELPFUL_LINKS', but instead it is 'Text'.
Okay, I figured this out on my own. The thing I was missing was that in even though I set the variable tagText = blkTag.getElement().asText(), in order to actually see the text, I had to use tagText.getText(). This was not intuitive.
Here is my final code that finds the tag and replaces it with the contents of the file that is named the same name as the tag.
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
});
}
}
}