elapouya / python-docx-template

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

Nested for in table #547

Open jodyphelan opened 5 months ago

jodyphelan commented 5 months ago

Describe your problem

I would like to create a table like the example image below. I tried to use a nested for loop like

image

However this seems to ignore the initial loop and gives this:

image

Is there a way of using nested loops?

More details about your problem

Here is the code used to render the template:

from docxtpl import DocxTemplate

tpl = DocxTemplate('template.docx')

context = {
    'data': [
        {'type': 'Fruit', 'names': ['Apple', 'Banana']},
        {'type': 'Vegetable', 'names': ['Carrot', 'Onion']},
    ]
}

tpl.render(context)
tpl.save('output/result.docx')
colorthoro commented 4 months ago

I have the same question. It seems like nested tr loops are not supported yet. Will this be added to the plan? It would be very useful. @elapouya

dukre commented 3 months ago

Hi, this template produces the desired output:

nested_tr

jodyphelan commented 1 month ago

Amazing thanks @dukre

jodyphelan commented 1 month ago

@dukre thanks for your answer. I thought I could expand your solution to an extra inner loop but it didn't seem to give the desired result. Any suggestions would be appreciated!

The desired table would look like:

image

The current template looks like this:

image

But this produces the following:

image

Here is the code:

from docxtpl import DocxTemplate

tpl = DocxTemplate('template.docx')

context = {
    'data': [
        {
            'type': 'Fruit', 'items': [
                {
                    'name':'Apple', 
                    'colours':[
                      'green', 
                      'red'
                    ]},
                {
                    'name':'Banana', 
                    'colours':[
                        'yellow'
                    ]
                }
            ]
        },
        {
            'type': 'Vegetable', 'items': [
                {
                    'name':'Carrot', 
                    'colours':[
                        'orange'
                    ]
                },
                {
                    'name':'Onion', 
                    'colours':[
                        'white', 
                        'red'
                    ]
                },
            ]
        }
    ]
}

tpl.render(context)
tpl.save('result.docx')