Search code examples
javascriptdocxtemplater

Docxtemplater. Nested objects


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.


Solution

  • There are two possibilities, one with angular-expressions, one without.

    With angular expressions

    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 */);
    

    Without angular expressions

    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.