elapouya / python-docx-template

Use a docx as a jinja2 template
GNU Lesser General Public License v2.1
1.92k stars 378 forks source link

Tables: Multiple loops in the same row #509

Open marcus-hao opened 10 months ago

marcus-hao commented 10 months ago

I am trying to query data for multiple columns using for loops for each column(they are all on the same row). I think something is wrong with the logic of my template, because the data in the last column will overwrite previous columns.

The code:

from docxtpl import DocxTemplate

context = {
    "previous_previous_year" : {
        "p1_events" : [
            {
                "classification" : "Event A",
                "count" : 4
            },
            {
                "classification" : "Event B",
                "count" : 1
            }
        ],
    },
    "previous_year" : {
        "p1_events" : [
            {
                "classification" : "Event A",
                "count" : 1
            },
            {
                "classification" : "Event B",
                "count" : 1
            }
        ],
    },
    "current_year" : {
        "p1_events" : [
            {
                "classification" : "Event A",
                "count" : 1
            },
            {
                "classification" : "Event B",
                "count" : 5
            }
        ],
    },
}

doc = DocxTemplate("template.docx")
doc.render(context)
doc.save("results.docx")

Screenshots

Template template

Expected Expected

Output Output

SergeyZaykov commented 7 months ago

You should use the for loop in one column only but loop variable 'event' in all columns. Open any table example like https://github.com/elapouya/python-docx-template/blob/master/tests/templates/dynamic_table_tpl.docx