-
Notifications
You must be signed in to change notification settings - Fork 425
Open
Labels
Description
Describe your problem
I want to insert multiple sub documents in a loop. I can get this to work, but there is always an extra paragraph symbol after each insertion that I do not want to be there.
More details about your problem
This is the result that I am getting:

And this is the result that I want to get / am expecting:

Provide a test case
Python code:
import json
from docxtpl import DocxTemplate
from jinja2 import Environment, Undefined
class CustomUndefined(Undefined):
def __str__(self):
return f"[[{self._undefined_name}]]"
def main():
# Setup stuff
jenv = Environment(undefined=CustomUndefined)
with open("json/test-example.json", "r") as ctx_file:
ctx: dict = json.load(ctx_file)
# Initialize the master document
doc = DocxTemplate("templates/Main.docx")
# Deal with the nested insert
subdocs = []
for data in ctx.get("houses", []):
sub_doc_tpl = DocxTemplate("templates/Property.docx")
sub_doc_tpl.render(context=data, jinja_env=jenv)
# Create a new subdoc, and replace the content with the content from the rendered template itself
sd = doc.new_subdoc()
sd.subdocx = sub_doc_tpl.docx
subdocs.append(sd)
ctx.update({"subdocs": {"houses": subdocs}})
# Render and save the master document
doc.render(context=ctx, jinja_env=jenv)
doc.save("./output/generated_doc.docx")
if __name__ == "__main__":
main()And this is the json file stored at ./json/test-example.json which my python code is reading in as the context.
{
"houses": [
{
"address": {
"street": "123 Main Street",
"city": "Kansas City",
"state": "Kansas",
"zip": "66215"
},
"owner": {
"name": "Sabrina W. Smith",
"age": 35
}
},
{
"address": {
"street": "4561 Raoul Wallenberg Place",
"city": "New London",
"state": "Connecticut",
"zip": "06320"
},
"owner": {
"name": "Pamela Brown"
}
}
]
}Property.docx template (that gets repeated for each house object in the context json):

