Docxtemplater angular-expressions not working for nested objects

312 Views Asked by At

I'm trying to generate a .docx file with docxtemplater in nodejs. I am also using the angular-expressions library as per their instructions in the docs. The issue is that every time I try to access a nested object's field, I get undefined in the generated documents. I can't seem to figure out what I am doing wrong ... In the template file I am accessing the field with {field.property}.

const PizZip = require("pizzip");
const Docxtemplater = require("docxtemplater");
const angularParser = require("docxtemplater/expressions");

const fs = require("fs");
const { getTemplateFilePath, getGeneratedFilePath } = require("./files.utils");

function generateAnnex1(data, outputName) {
  const templatePath = getTemplateFilePath("annex_1");
  const ouputPath = getGeneratedFilePath("annex_1", outputName);

  generateDoc(templatePath, ouputPath, data);
}

function generateDoc(templatePath, outputPath, data) {
  const content = fs.readFileSync(templatePath, "binary");
  const zip = new PizZip(content);

  const doc = new Docxtemplater(zip, {
    parser: angularParser,
  });

  doc.render(data);

  const buf = doc.getZip().generate({
    type: "nodebuffer",
    compression: "DEFLATE",
  });

  fs.writeFileSync(outputPath, buf);
}
1

There are 1 best solutions below

0
Sandun Isuru Niraj On

Change this part,

  const doc = new Docxtemplater(zip, {
    parser: angularParser,
  });

to like this,

  const expressionParser = require('docxtemplater/expressions.js')
  const doc = new Docxtemplater(zip, {
    parser: (tagString) => {
            const parser = expressionParser(tagString);
              return {
                get(scope, context) {
                  const module =
                  context &&
                  context.meta &&
                  context.meta.part &&
                  context.meta.part.module;
                  const isIncludeTag =
                    [
                      "pro-xml-templating/subsection-module",
                      "pro-xml-templating/replacesection-module",
                    ].indexOf(module) !== -1;
                    const value = parser.get(scope, context);
                    if (isIncludeTag && value) {
                      value.render(scope);
                    }
                    return value;
            },
         };
      },
  });