使用docxtpl插入两个子文档后模板尾部内容丢失问题求助
docxtpl 插入多子文档后模板尾部内容丢失的问题解决
在使用docxtpl将多个生成的子文档插入模板时,仅第一个子文档生效,后续子文档及模板尾部内容全部消失,具体情况如下:
模板内容(template.docx)
some text {{p subdoc1}} again some text {{p subdoc2}} and at the end of the document also some text
测试代码
from docxtpl import DocxTemplate doc = DocxTemplate("docx_template.docx") sd1 = doc.new_subdoc() sd1.add_paragraph("First subdoc") sd2 = doc.new_subdoc() sd2.add_paragraph("Second subdoc") context = {"subdoc1" : sd1, "subdoc2" : sd2} doc.render(context) doc.save("output.docx")
预期输出
some text First subdoc again some text Second subdoc and at the end of the document also some text
实际输出
some text First subdoc
环境版本
- Python 3.9.12
- docxtpl 0.11.5 / 0.16.4(两个版本表现一致)
- python-docx 0.8.11
问题原因及解决方案
该问题源于docxtpl处理{{p}}标签的机制:{{p subdoc}}会替换当前段落并清除后续段落的引用关联,导致模板中该标签之后的所有内容无法被渲染。
解决方式是将模板中的{{p}}标签替换为{{r}}标签,{{r subdoc}}会在当前位置插入子文档内容,同时保留后续模板内容的渲染关联。
修改后的模板内容:
some text {{r subdoc1}} again some text {{r subdoc2}} and at the end of the document also some text
运行原测试代码即可得到符合预期的输出文档。
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

