elapouya / python-docx-template

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

Corrupt document when passing a context with nested objects that have the word `pop` in the keys #496

Open maarten-betman opened 1 year ago

maarten-betman commented 1 year ago

Describe the bug

When passing a context object that has a nested object with word pop as on the keys, the render goes fine, but when trying to open the word document you are told the document is corrupted.

To Reproduce

Any word file should reproduce this bug if a context object is passed containing pop.

word contents:

image

code

from docxtpl import DocxTemplate

doc = DocxTemplate("test.docx")
doc.render(context={"pop": 2, "soil": {"pop": 2}})
doc.save("rendered.docx")

Expected behavior

Expecting all object to render

Screenshots

image

Additional context

POP is a soil variable which is used in geotechnical engineering.

Pop is off course a method of a dictionary object, but was not expected that a pop method would be called in Jinja. I would like to make a PR for this to either give the user a warning, raise a error (ValueError?) during rendering or make not of this behavior in the docs

elapouya commented 1 year ago

I think because pop is a function it will return the function representation which should look like something like :

<built-in method pop of dict object at 0x7fd349ddd140>

Which is not a valid xml tag, that's why the generated it not valid too. You can use autoescape=True in render() method to confirm that. You have to avoid using dict methods with dotted notation, please try :

{{ soil['pop'] }}

In your template instead.

maarten-betman commented 1 year ago

Thanks for the quick response! Confirmed that autoescape=True returns the function representation and that {{ soil['pop'] }} does render the correct results.

Would you accept a PR that introduces a warning or ValueError when a method of json is called with dot notation?

elapouya commented 1 year ago

You can propose a PR to add a note in the manual