j_allen_morris
j_allen_morris

Reputation: 599

Looping through a list (or dict) when using python-docx-template (docxtpl)

EDIT: I must admit I screwed up and hadn't downloaded all of the examples/tests. I downloaded the entire package and found awesome examples that showed me how to do everything I wanted to do. This particular issue is shows in dynamic_table_tpl.py and dynamic_table.docx.

I am using python-docx-template and have created a DOCX template. I have been trying to use jinja2 formatting as the documentation suggests. I need to add a series of addresses into my DOCX file. That data is from a database and I'm pulling it from the DB using python.

Here's what I have in the DOCX Template file:

{% for kid in kids %}
{kid.first}{kid.last}
{kid.addr1}{kid.addr2}
{kid.city}{kid.state}{kid.zip}  

{% endfor %}

This is in my .py file:

kids = [
    [
        ('first','John'),
        ('last','Williams'),
        ('addr1','5555 NW 37th St')
        ('addr2','Apt 2601')
        ('city','Oklahoma City')
        ('state','OK')
        ('zip','73112')
    ],
    [
        ('first','George'),
        ('last','Lucas'),
        ('addr1','1234 Dobbs St.')
        ('addr2','Suite 62')
        ('city','Moore')
        ('state','OK')
        ('zip','73160')
    ]
]

context = {
    "kids" : kids
}

I've looked in the documentation and examples and have not found out how to make this work. If I have 2 kids in the database, I would like the result to look something like this:

John Williams
5555 NW 37th St., Apt 2601
Oklahoma City, OK 73112

George Lucas
1234 Dobbs St., Suite 62
Moore, OK 73160

The template is not replacing anything in the loop. It is writing both of the loops in the created DOCX where in the Template I have the for kid in kids loop only written once. It's reading it in some way, but not exactly how I need it to work.

Any help is greatly appreciated!

Upvotes: 3

Views: 7010

Answers (1)

Pasan Chamikara
Pasan Chamikara

Reputation: 755

While using tuples (the bracket thing) , it is not possible to reach the elements without a numeric index. Therefore the best thing to do is accessing them via an index like kid[1], or otherwise turn the tuple into a dictionary prior accessing it (IMO this is the most reliable)

Upvotes: 4

Related Questions