0

I’m trying to fill a .docx template using the docxtpl library in Python, but I need to do it in multiple steps, because I can’t load the entire context dictionary into memory at once.

The problem is that after the first render() call with a partial context, docxtpl removes all Jinja2 variables and blocks that were not provided, which makes it impossible to fill the remaining placeholders later.

Here is a simplified example:

import re
from docxtpl import DocxTemplate

# First render
doc = DocxTemplate("template.docx")
doc.render({
    "TABLE": [
        {"a": 1, "b": 4},
        {"c": 3, "d": 7}
    ],
})

# Second render
doc.render({
    "ANOTHER_TABLE": [
        {"a": 5, "b": 7},
        {"c": 5, "d": 5}
    ],
})

doc.save("_generated.docx")

After the first render step, any remaining variables or Jinja2 blocks (such as {{ ANOTHER_TABLE }} or {% for ... %}) are removed from the document, so the second render does nothing.

Question:
Is there a way to perform multiple partial render() calls with docxtpl without stripping out unresolved variables or blocks?

Alternatively, is there any known workaround (such as freezing rendered parts, using placeholder indirection, or another technique) that allows a template to be processed in multiple steps?

New contributor
MathW166 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.