I would like to use jinja2 for word templating like mentioned is this short article. The problem I'm facing is as follows, if I put {{title}}
in my word-file the resulting xml can look like this:
<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></w:p>
so it is impossible for jinja to replace this accordingly. Is there a possibility to prevent word from splitting {{title}}
in separate text elements? (if I copy from a text-editor it works fine)
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 DocxTemplatedoc = 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?