I am using Python-Docx-Template to dynamically create address labels that can be printed on Avery labels. I have found the correct table template in MS Word and have inserted a FOR loop to go through the addresses. There are 3 addresses per line, so I have set up the code like this:
from docxtpl import DocxTemplate
tpl=DocxTemplate('templates/address_labels.docx')
context = {
'tbl_contents' : [
{'addrs':[
{'addr_count':1,'first':'Peyton','last':'Manning','addr1':'123 Cherry St.','city':'Denver','state':'CO','zip':'12345'},
{'addr_count':2,'first':'Patrick','last':'Mahomes','addr1':'123 KC BBQ Blvd','city':'Kansas City','state':'MO','zip':'12345'},
{'addr_count':3,'first':'Tom','last':'Brady','addr1':'123 New England Cir','city':'Boston','state':'MA','zip':'12345'}]},
{'addrs':[
{'addr_count':1,'first':'Drew','last':'Brees','addr1':'123 Nola Way','city':'New Orleans','state':'LA','zip':'12345'},
{'addr_count':2,'first':'Phillip','last':'Rivers','addr1':'123 Beachside Dr.','city':'Los Angeles','state':'CA','zip':'12345'},
{'addr_count':3,'first':'Kyler','last':'Murray','addr1':'123 Dusty Rhoads Dr','city':'Phoenix','state':'AZ','zip':'12345'}
]}
]
}
tpl.render(context)
tpl.save('output/addr_labels.docx')
My word Template is:
I'm doing the table this way because the Avery address labels have the thin table cell in between the larger cell where the address goes. This helps with formatting. If I remove the IF statement, everything works okay, but there is the extra little table cell at the end because I'm repeating the big table cell and the thin table cell for all three addresses on the line. It's not a HUGE issue, but I would would really like to have that thin table cell NOT entered if the addr_count == 3
(I have tried addr_count == '3'
and addr_count == 3
and having quotes around the number didn't make any difference.
Here is the error I'm getting.
Does anyone know how to use an IF statement nested inside a FOR loop in python-docx-template?
Place the {% endif %}
inside of the small cell instead of after it.
I'm not sure why this works, I actually spent a decent amount of time trying to puzzle out the logic. But if it works, it works.