Search code examples
pythonjinja2template-enginedocx

Jinja2 for word templating


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)


Solution

  • 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