【发布时间】:2015-05-18 13:56:46
【问题描述】:
我正在使用 django 创建一个 XML 文档,并查看 XSD 架构,可能需要也可能不需要很多标签。
像这样:
<GenericCustomerPaymentDetails>
<PayPalID>{{purchase.customer.ppid}}</PayPalID>
<BankAccountNumber>{{purchase.customer.ban}}</BankAccountNumber>
<SortCode>{{purchase.customer.sc}}</SortCode>
<CreditCardNumber>{{purchase.customer.ccn}}</CreditCardNumber>
<BitCoinAddress>{{purchase.customer.bitcoin}}</BitCoinAddress>
</GenericCustomerPaymentDetails>
现在,我知道如何单独指定标签可能存在也可能不存在(包装在 if/endif 标签中),但这样做会使文档大小增加三倍,并且维护量会增加一倍:
<GenericCustomerPaymentDetails>
{% if purchase.customer.ppid %}
<PayPalID>{{purchase.customer.ppid}}</PayPalID>
{% endif %}
{% if purchase.customer.ban%}
<BankAccountNumber>{{purchase.customer.ban}}</BankAccountNumber>
{% endif %}
{% if purchase.customer.sc %}
<SortCode>{{purchase.customer.sc}}</SortCode>
{% endif %}
{% if purchase.customer.ccn %}
<CreditCardNumber>{{purchase.customer.ccn}}</CreditCardNumber>
{% endif %}
{% if purchase.customer.bitcoin %}
<BitCoinAddress>{{purchase.customer.bitcoin}}</BitCoinAddress>
{% endif %}
</GenericCustomerPaymentDetails>
如果有更优雅的方式来做到这一点?有没有办法将 if 存在批量应用于值和标签? (如果解决方案可以容纳 stags [自闭合标签],则加分)
我能想到的唯一方法就是将这些支付方式变成 json 上的对象列表,就像这样
purchase.customer:[
{tag_name:"PayPalID",tag_content:"pay.me.monies@geemail.com"},
{tag_name:"BitCointAddress",tag_content:"http://blockexplorer.com/address/1PC9aZC4hNX2rmmrt7uHTfYAS3hRbph4UN"},
]
然后循环遍历它们。但这将需要额外的数据操作才能进入这种格式,我宁愿不必经历这种努力(如果看起来像 this 是要走的路,如果你已经有这样的数据的话。)。
【问题讨论】:
标签: python xml django django-templates