handle undefined values in docXTemplater or javascript object array

2.7k Views Asked by At

I have an object array that will be exported to word document via DocXTemplater

Sample array

[
{Name:"jon doe",age:27}
{Name:"joe roe",age:27,Address:"new jersey"}
]

Now the DocXTemplate will be

{#arrayVarName}{Name},{age},{Address}{/arrayVarName}

This will output,

Jon,27,undefined
Joe,27,new jersey

Now I want to filter all undefined and replace them with either empty string or some custom string, how can this be done in DocXTemplater, or can all the undefined in object array be replaced with custom string?

4

There are 4 best solutions below

0
On BEST ANSWER

You can now customize this setting globally :

const doc = new Docxtemplater(zip, {nullGetter() { return ''; }});
0
On

Since Docxtemplater V4, you should not use this :

doc.setOptions({...})

Instead, you should specify options during doc construction :

const doc = new Docxtemplater(zip, {nullGetter() { return ''; }});
0
On

I was trying to handle it with doc.setOptions() but had this error:

setOptions() should not be called manually when using the v4 constructor

What I had to do is to change this part of the code to show empty space instead of undefined:

doc=new window.docxtemplater(zip, {nullGetter() { return ''; }});

Thanks to Dorpaxio. But in my case it didn't work with:

const doc = new Docxtemplater();
1
On

Use angular parser to eliminate undefined or null

expressions= require('angular-expressions')
angularParser= function(tag){
    expr=expressions.compile(tag);
    return {get:expr};
}

Set the parser using the below code

    doc=new DocxGen(content)
    doc.setOptions({parser:angularParser})

In the template use the below code

{#value!=undefined}{value}{/value!=undefined}