【问题标题】:How to apply conditional attribute to HTML element in template?如何将条件属性应用于模板中的 HTML 元素?
【发布时间】:2015-04-23 01:47:38
【问题描述】:

我的模板中有一个复选框。如果对象布尔字段为 True,我希望检查该复选框。

我的 html 元素看起来像:

<div class="checkbox"><label>
<input type="checkbox" name="sendEmail" checked="{{ customer.SendSms }}">
Send sms?
</label></div>

问题是,当属性checked="False" 时,复选框仍然被选中,只有当checked 属性不存在时,它才会被取消选中。

所以我需要的是,只有当customer.SendSms 为真时,才将选中的属性放入 html 元素中。

我知道类似的东西

{% if customer.SendSms %}
//checked html element here
{% else %}
//unchecked element here
{% endif %}

可能,但这看起来不那么漂亮,有没有其他好的方法来处理这个问题?

【问题讨论】:

    标签: python django python-2.7 django-templates


    【解决方案1】:

    为什么不将属性包装在条件中?

    <input type="checkbox" name="sendEmail" {% if customer.SendSms %}checked{% endif %}>
    

    【讨论】:

      【解决方案2】:

      yesno 模板过滤器将完成这项工作:

      <input type="checkbox" name="sendSms" {{ customer.SendSms|yesno:"checked" }}>
      

      【讨论】:

      猜你喜欢
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 2019-10-01
      • 1970-01-01
      • 2013-05-31
      相关资源
      最近更新 更多