Question

I have a block of XML that is returned from an API call.

It contains lots of results - person elements like below.

<root><person><name>mark</name><age>18</age></person><person><name>alan</name><age>10</age></person></root>

I want to pass this data structure (or some iterable version if it) to a django template to iterate over.

In my template I want to say

{% for r in results %}
{{ r.name }}
{{ r.age }}
{% endfor %}

I thought this would have been straight forward but its posing problems.

Was it helpful?

Solution

Django templates cannot handle it out-of-the-box. And it doesn't actually sound correct - to pass an XML structure into HTML template to process.

Making custom template tags or filters that would help to iterate over the XML structure could be a possible solution, but in this case you may find yourself overcomplicating things, template layer was made for presentation, don't put too much logic into it:

We see a template system as a tool that controls presentation and presentation-related logic – and that’s it. The template system shouldn’t support functionality that goes beyond this basic goal.

Parse the XML in the view, make a list of dictionaries and pass it to the template inside the context.

For example, use xmltodict tool:

persons = xmltodict.parse(data)['root']['person']

where data is your XML structure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top