处理 docXTemplater 或 javascript 对象数组中的未定义值

handle undefined values in docXTemplater or javascript object array

我有一个对象数组,将通过 DocXTemplater 导出到 word 文档

示例数组

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

现在 DocXTemplate 将是

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

这将输出,

Jon,27,undefined
Joe,27,new jersey

现在我想过滤所有未定义的并用空字符串或一些自定义字符串替换它们,这在 DocXTemplater 中如何完成,或者对象数组中的所有未定义是否可以替换为自定义字符串?

使用angular解析器消除undefined或null

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

使用以下代码设置解析器

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

在模板中使用以下代码

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

您现在可以全局自定义此设置:

https://github.com/open-xml-templating/docxtemplater/blob/bf51212c9821e40a9c3d18235427796df64d6bcb/docs/source/configuration.rst#nullgetter

doc=new DocxGen(content);
doc.setOptions({nullGetter: function() {
   return ""; 
}});

从 Docxtemplater V4 开始,您不应该使用它:

doc.setOptions({...})

相反,您应该在文档构建期间指定选项:

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

我试图用 doc.setOptions() 处理它,但出现了这个错误:

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

我必须做的是更改这部分代码以显示空 space 而不是 undefined:

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

感谢Dorpaxio。但就我而言,它不适用于:

const doc = new Docxtemplater();