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)
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
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?
来源:https://stackoverflow.com/questions/28488090/jinja2-for-word-templating