【问题标题】:Is there an elegant way to apply {% if .. %} to a whole load of tags in Django?有没有一种优雅的方法可以将 {% if .. %} 应用于 Django 中的所有标签?
【发布时间】: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


    【解决方案1】:

    您可以编写一个自定义过滤器来检查该值是否存在并使用正确的 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

    【讨论】:

    • 这或多或少是我刚刚写的!感谢您指出它是多么简单。我唯一的区别是我使用的是one line if statement
    猜你喜欢
    • 2010-12-10
    • 2021-08-14
    • 2016-11-24
    • 2021-12-19
    • 2023-03-31
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多