有没有一个优雅的方法来应用{%if。。%}在Django有一大堆标签?

2024-10-03 15:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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 exists批量应用于值和标记?(如果解决方案可以容纳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是一种方式,如果您已经有了这种方式的数据)。你知道吗


Tags: 方法标记iftagcustomerpurchasescendif
1条回答
网友
1楼 · 发布于 2024-10-03 15:23:11

您可以编写一个自定义过滤器来检查值是否存在,并使用正确的XML标记对其进行包装。例如:

def default_xml_tag(value, arg):
    if value:
        return "<{0}>{1}</{0}>".format(arg, value)
    else:
        return ""

简单地写下

{{purchase.customer.ppid | default_xml_tag:"PayPalID" }}

在模板中。你知道吗

有关如何注册过滤器的详细信息,请参阅(极好的)Django docs。你知道吗

相关问题 更多 >