Jinja2 for word templating

让人想犯罪 __ 提交于 2019-12-03 17:32:05

This is an issue that is in word, relating to the proofErr tag.

You have two solutions:

  • If you want to stick with Jinja2, you should always write your tags in one stroke. Eg, never hit backspace or edit a tag. You can also copy/paste it from an other editor.

  • I wrote a library, Docxtemplater that works even if the text-elements are splitted, eg it would replace:

    <w:r>
     <w:t>
       {{
     </w:t>
    </w:r>
    <w:proofErr w:type="gramStart"/>
     <w:r>
      <w:t>title</w:t>
     </w:r>
    <w:proofErr w:type="gramEnd"/>
     <w:r>
      <w:t>}}</w:t>
     </w:r>
    

    by:

    <w:r>
      <w:t>
        Your title
      </w:t>
    </w:r>
    <w:proofErr w:type="gramStart"/>
    <w:r>
      <w:t></w:t>
    </w:r>
    <w:proofErr w:type="gramEnd"/>
    <w:r>
      <w:t></w:t>
    </w:r>
    

Docxtemplater can be programmed over a CLI or in JS Browser/Node.JS

Nathan Basanese

https://pypi.org/project/docxtpl/ is also a good alternative.

It extends python-docx, and allows you to just drop in Jinja2 tags wherever you want in an existing .docx document, rather than templating from scratch.

Example:

pip install docxtpl

Usage:

from docxtpl import DocxTemplate

doc = DocxTemplate("my_word_template.docx")
context = { 'company_name' : "Dr. Stubbs Orthopedics and Prosthetics" }
doc.render(context)
doc.save("generated_doc.docx")

If your template my_word_template.docx file looks like this:

[

Then your generated_doc.docx will look like this:

Relatively simple, right?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!