python-docx-template icon indicating copy to clipboard operation
python-docx-template copied to clipboard

Using the loop variable in header

Open PH8919 opened this issue 2 years ago • 5 comments

Hi, guy I want to generate a document with different header text and my exmaple data is : data = [{hdr:"a"},{hdr:"b"},{hdr:"c"}]

My example template contains three pages: page 1: no header and tranverse the data using "{% for item in data %}" page 2: its header is "{{ item.hdr }}" page 3: no header and end for loop with "{% endfor %}"

when I run this exmple, it reports a error " hdr of undefined". So how can i revise it, anyone can help me? thanks.

PH8919 avatar Jun 27 '23 11:06 PH8919

Declare your list named data like this, [{"hdr" : "a"}, {"hdr" : "b"}, {"hdr" : "c"}]

Tanishqmalu avatar Jul 08 '23 03:07 Tanishqmalu

@Tanishqmalu Sorry I didn't format the data type on web corrently. My local data is as you listed. Thanks.

PH8919 avatar Jul 08 '23 06:07 PH8919

@PH8919 Probably

{{ item["hdr"] }}

is correct syntax to access key of dictionary?

SergeyZaykov avatar Jul 31 '23 19:07 SergeyZaykov

@PH8919 Probably

{{ item["hdr"] }}

is correct syntax to access key of dictionary?

Hi, guy

I think my syntax is correct, you can refer to jinja2 tutorial.

Thanks

PH8919 avatar Aug 01 '23 00:08 PH8919

Hi, guys

I think it is because the header and footer are in defferent files for XML and rendered firstly. But the for loop is in written in document file. So when rendering the header and footer, it can access the loop variables. Fortunately, I found a alternative method, user can render the whole document in different DOCX files with separate chapter, and you can promote the header/footer data to be global. then using the docxcomposer to compose the separate documents.

Thanks

PH8919 avatar Aug 01 '23 00:08 PH8919