I'm using https://github.com/open-xml-templating/docxtemplater
My data:
var person = {
name: 'Joe',
address: {
city: 'Stockholm',
postal: 45123
}
}
How do write the syntax in the docx with this nested object?
This is not working:
{address.city}
Can't find any example in the docs.
There are three possibilities, one with angular-expressions, one by writing a very simple parser yourself, or one without any parser.
The "angular-expressions" parser gives you the ability to parse more complex expressions :
{address.city}
To use it you also have to install angular-expressions
:
npm install --save angular-expressions
const expressionParser = require("docxtemplater/expressions.js");
const doc = new Docxtemplater(zip, { parser: expressionParser });
doc.render(/* data */);
const doc = new Docxtemplater(zip, {
paragraphLoop: true,
linebreaks: true,
parser(tag) {
const splitted = tag.split(".");
return {
get(scope) {
if (tag === ".") {
return scope;
}
let s = scope;
for (
let i = 0, len = splitted.length;
i < len;
i++
) {
const key = splitted[i];
s = s[key];
}
return s;
},
};
},
});
doc.render({
user: {
name: "John",
},
});
This allows you to parse {user.name}
with nested property access.
If you don't want to add a parser option (which relies on an external dependency), you will have to write in your template :
{#address}{city}{/}
This creates a section that will have as current context the "address" object, and then fetch the "city" key from the address object.