1

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
  • Did you find out how to do it ? If it still does not work, please provide the data that you are using. It should be something like this : const data = { field : { property: "John" }} Commented May 22, 2023 at 13:43

1 Answer 1

-1

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;
            },
         };
      },
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.