Jinja2 for word templating

你。 提交于 2019-12-05 02:37:06

问题


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)


回答1:


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




回答2:


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

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