0

I am using docxtpl module to generate handful of documents with the data that I have. My data are stored as a list of dictionaries. I have written a for loop for that, yet in each iteration my for loop generates a docx document with the information of the first dictionary! Do you have any idea how I can fix this?

I leave a sample Python code here so as to give a better overview of the problem!

from docxtpl import DocxTemplate
from docx2pdf import convert

doc = DocxTemplate('Hello.docx')

list = [{'name': 'John'}, {'name': 'Amin'}, {'name': 'Carl'}]

for i in range(3):
    doc.render(list[i])
    doc.save('test'+str(i)+'.docx')

My docx is as simple as:

Hello my name is {{ name }}

I want to generate 3 different word documents with the names John, Amin, and Carl.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Aminem666
  • 1
  • 1

1 Answers1

1

Your for loop is kind of messed up. And the variable list is protected, so you should rename the list:

list_of_names = [{'name': 'John'}, {'name': 'Amin'}, {'name': 'Carl'}]

I would instead loop over the list itself, and access the values straight from there.

for item in list_of_names:
    doc.render(item)  
    doc.save(f"test{item['name']}.docx")

I'm not sure, but you may need to open the template document with each iteration. In that case, the code should look like this:

for item in list_of_names:
    doc = DocxTemplate('Hello.docx')
    doc.render(item)  
    doc.save(f"test{item['name']}.docx")

Please, let me know if it works as expected :)

ish
  • 75
  • 5