javascriptnode.jsdocxtemplater

How to build a list in a word file with docxtemplater?


My template file (i.e. template.docx) is shown as the following:

enter image description here

My node.js code:

let Docxtemplater = require('docxtemplater');
let fs = require('fs');
let path = require('path');
let PizZip = require('pizzip');
let content = fs.readFileSync(path.resolve(__dirname, 'template.docx'), 'binary');
let zip = new PizZip(content);
let doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true });

let statData = {items:[{"name":"item 1","desc":"xxx\nyyyy" },{"name":"item 2","desc":"www\njjj"}]};
doc.setData(statData);
doc.render();
let buf = doc.getZip().generate({ type: 'nodebuffer' });
fs.writeFileSync(path.resolve(__dirname, 'output.docx'), but);

I expected the resultant word file should be as below:

enter image description here

However, the actual result is something like below:

enter image description here

I have created a list in the "item description" cell.

However, the actual result does not work as my expectation.

How can I fix the problem?


Solution

  • In your data you have :

    {
      items: [
        { name: "item 1", desc: "xxx\nyyyy" },
        { name: "item 2", desc: "www\njjj" },
      ];
    }
    

    And in your template, you use :

    - {desc}
    

    This will indeed just add a newline to the list, not create a new list item.

    To create a new list item, I would change the structure to this :

    {
      items: [
        { name: "item 1", desc: ["xxx", "yyyy"] },
        { name: "item 2", desc: ["www", "jjj"] },
      ];
    }
    

    And in your template :

    - {-w:p desc}{.}{/}
    

    This can also be tested online with this demo : https://docxtemplater.com/demo/#loop-list