Placeholders not replaced inside a docx template

345 views Asked by At

I'm using this library to replace some placeholders into a docx template and generate multimple documents. I'm using neutralino and vue for the front-end and I've created a method that will pass the selected docx file and the data to the library for processing. I've used a for loop in this way

// putting all the desired data into a specific array
for(let i = 0; i < this.selectedData.length; i++){
  this.dataPlaceholders.push({
   key1: val1,
   key2: val2
  })
}
//call the library to get documents

for(let i; i < this.dataPlaceholders.length; i++){
 this.docxTemplate.process(template, this.dataPlaceholders[i])
}

the data to pass are merged from two array and if I console log them I'm able to see that all si in place. As explained into the docs, I'm using the brackets {} to set the placeholders and the name of the placeholders is the same that I have for each key in the dataPlaceholders array. After A test I've noticed that I'm able to generate different documents, but the placeholders will be not replaced and I will have blank fields into the documents.

How I can fix it to make this owrk correctly?

2

There are 2 answers

0
newbiedev On

After some tries and after reading some questions on how to implement an async call inside a loop, I've opted to use the Array.prototype.map function and it's working fine. I've modified my vue method that is calling the library to an async method, but I leave untuched the then block so I will be able to get the processed documents after the library finished processing them.

this.dataPlaceholders.map( async (data, i) => {
  let filename = data.supplier + '.docx'
  this.docxTemplate.process(template, data).then( (result) => {
    // code to download files here
     let a = document.createElement('a')
     let downloadLink = URL.createObjectURL(result)
     a.href = downloadLink
     a.download = filename
     a.click()
  })
})

The only thing to solve is how I can revoke the blob url after all files are downloaded.

0
ICTDEV On

My suggestion is to use a for loop instead of the map function, if your function is async you can try using this code

async function myFunc(){
    for( let i = 0; i < myArray.length; i++ ){
        await functionTocall(param1, param2)
    }
}

The for loop will wait until the async function return a promise, in this way you will be sure that the function inside the loop will be executed correctly.