[Python] Python-docx-template (docxtpl) dynamic table in if-statement

Discussão em 'Python' iniciado por Stack, Março 31, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to generate Word documents with python-docx-template. Below is a small subset of my data. My data is one large array of objects with the same structure. However, sometimes the value for 'answer' is a string and sometimes it is an array of objects. If the answer is an array of objects, I want the data to be displayed in a MS Word table. If the answer is a string, I just want to display the string.

    Since my actual data contains many objects, I do not want to define every table manually. I am currently receiving the error below. Can anyone please help me?

    Error

    File "<unknown>", line 8, in template
    jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endfor'. You probably made a nesting mistake. Jinja is expecting this tag, but currently looking for 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.


    Data

    {
    "data": [
    {
    "title": "title 1",
    "subtitle": "subtitle 1",
    "question": "Lorem ipsum? 1",
    "summary": "Lorem ipsum 1",
    "answer": "Lorem ipsum 1"
    },
    {
    "title": "title 2",
    "subtitle": "subtitle 2",
    "question": "Lorem ipsum? 2",
    "summary": "Lorem ipsum 2",
    "answer": [
    {
    "office": "Office A",
    "address": "Lorem ipsum",
    "postal_code": "Lorem ipsum",
    "city": "Lorem ipsum",
    "country": "Lorem ipsum",
    "coordinates": "Lorem ipsum"
    },
    {
    "office": "Office B",
    "address": "Lorem ipsum",
    "postal_code": "Lorem ipsum",
    "city": "Lorem ipsum",
    "country": "Lorem ipsum",
    "coordinates": "Lorem ipsum"
    }
    ]
    },
    {
    "title": "title 3",
    "subtitle": "subtitle 3",
    "question": "Lorem ipsum? 3",
    "summary": "Lorem ipsum 3",
    "answer": [
    {
    "Name": "Name A",
    "Job": "Job A",
    "Age": "Age A"
    },
    {
    "Name": "Name B",
    "Job": "Job B",
    "Age": "Age B"
    }
    ]
    }
    ]
    }


    Template Template

    Desired output Desired output

    Continue reading...

Compartilhe esta Página