【问题标题】:How to render docxtemplater multiple times with different data sets如何使用不同的数据集多次渲染 docxtemplater
【发布时间】:2021-06-14 13:41:03
【问题描述】:

我使用 docxtemplater 将 Word 文档(我从云端加载)中的标签替换为实际值。

我使用的 Word 文档包含任意标签,因此我首先需要检查一个 Word 文档并获取它包含的所有标签的列表。为此,我使用InspectModule,它被设置为docxtemplater.render() 的一个选项。然后我查询一个服务,我使用标签作为动态查询的参数。最后,我通过调用docxtemplater.setData(myData) 后跟(再次)docxtemplater.render(),将标签替换为各种查询结果。

问题是,当我用InspectModule 调用docxtemplater.render() 时,模块不仅获取所有标签(这很好),它还将Word 文档中的所有标签替换为字符串“未定义”(这对我的目的不利),因为我不想用字符串“undefined”替换标签,而是用我的查询结果转换为数据对象。

解决此问题的最佳方法是什么(本质上,我希望能够多次调用render())?从云端重新加载 Word 文档,并使用查询的数据再次从新的docxtemplaterrender() 开始?在第一次调用render() 之前深复制docxtemplater 对象,所以我有一个docxtemplater 对象的“新”副本,可以用于第二次render() 调用?或者我可以使用参数调用render(),这样它就不会修改文档,或者是否有reset() 方法,将docxtemplater 对象设置回render() 方法执行之前的状态?还是有其他更好的选择?谢谢!

代码:这将获取所有标签,并将 Word 文档中的所有标签替换为字符串“undefined”。

const iModule = InspectModule();
const options = {modules: [this.iModule]};
const data = await fetch("something.docx");
const zip = new PizZip(data);
const document = new Docxtemplater(zip, options);
document.render();
const tags = Object.keys(this.iModule.getAllTags());

【问题讨论】:

    标签: javascript docxtemplater


    【解决方案1】:

    感谢您花时间详细解释您的问题。

    我更新了文档以将 doc.render() 放在 console.log 之后,并且我添加了一条注释,说明它对于检索文档的标签是可选的。

    关于您的问题,目前无法使用多个数据集呈现相同的 docxtemplater 实例,您需要使用新的 pizzip 实例和新的 Docxtemplater 实例(但是您可以保留相同的 inputBuffer)。造成这种情况的原因是因为我认为没有办法轻松克隆 pizzip 实例。但是这个想法一直在我的脑海中,尤其是对于 docxtemplater 版本 4。

    【讨论】:

      【解决方案2】:

      我发现 docxtemplater 常见问题解答 (https://docxtemplater.readthedocs.io/en/latest/faq.html#get-list-of-placeholders) 中给出的示例误导了我。事实上,您可以简单地省略对doc.render() 的调用,仍然可以获得所有标签。所以,问题可以这样解决:

      const iModule = InspectModule();
      const options = {modules: [this.iModule]};
      const data = await fetch("something.docx");
      const zip = new PizZip(data);
      const document = new Docxtemplater(zip, options);
      const tags = Object.keys(this.iModule.getAllTags());
      

      【讨论】:

        猜你喜欢
        • 2021-10-31
        • 1970-01-01
        • 1970-01-01
        • 2012-02-22
        • 2021-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多