【发布时间】:2013-12-28 06:57:57
【问题描述】:
我想格式化一些 XML 并将其传递给 Django 模板。在 shell 中,我可以使用以下代码成功创建 XML 字符串:
locations = Location.objects.all()
industries = Industry.objects.all()
root = ET.Element("root")
for industry in industries:
doc = ET.SubElement(root, "industry")
doc.set("name", industry.text)
for location in locations:
if industry.id == location.company.industry_id:
item = ET.SubElement(doc, "item")
latitude = ET.SubElement(item, "latitude")
latitude.text = str(location.latitude)
longitude = ET.SubElement(item, "longitude")
longitude.text = str(location.longitude)
然后,仍然在 shell 中,ET.dump(root) 输出我期望的 XML。
但是,如何使用 ET.dump(root) 将 XML 字符串从 Django 视图传递到模板文件?
我尝试使用'xml_items': ET.dump(root) 将它作为{{xml_items}} 传递,我还尝试将ET.dump(root) 分配给一个变量并像'xml_items': xml_items 一样传递它。
在这两种情况下,模板都会为{{xml_items}} 输出None
【问题讨论】:
标签: python django django-templates django-views elementtree