【问题标题】:Django - Template bitmask checkDjango - 模板位掩码检查
【发布时间】:2014-02-10 19:53:31
【问题描述】:

考虑这个列表:

options = [
    {
        'name': 'Option 1',
        'plan': 0b001,
    },
    {
        'name': 'Option 2',
        'plan': 0b010,
    },
    {
        'name': 'Option 3',
        'plan': 0b110,
    },
]

问题:如何将此列表显示为

         plan1 plan2 plan3
Option 1               ✔
Option 2         ✔      
Option 3   ✔     ✔      

来自类似的模板

{% for option as options %}
<div>
  <div>{{ option.name }}</div>
  <div>{{ option.plan|bitmaskcheck:0b001 }}</div>
  <div>{{ option.plan|bitmaskcheck:0b010 }}</div>
  <div>{{ option.plan|bitmaskcheck:0b100 }}</div>
</div>
{% endfor %}

使用一种bitmaskcheck 运算符? (或者会有更简单的?)

【问题讨论】:

  • 由于 Python 是非常高级的编程语言,我不会尝试创建位掩码,因为它会增加问题的复杂性而没有任何性能优势。相反,options.plan 对象可能是一个字典,其中您有 options.plan["plan1"] = True 或 False。然后你可以简单地检查一下 {{ option.plan.plan1 }}

标签: python django django-templates bitmask django-template-filters


【解决方案1】:

作为suggested by @MikkoOhtamaa,我将使用字典

options = [
    {
        'name': 'Option 1',
        'plan': {1: True,},
    },
    {
        'name': 'Option 2',
        'plan': {2: True,},
    },
    {
        'name': 'Option 3',
        'plan': {2: True, 3: True,},
    },
]

那么我应该能够进行以下检查:

{% for option as options %}
<div>
  <div>{{ option.name }}</div>
  <div>{% if option.plan.1 %}✔{% endif %}</div>
  <div>{% if option.plan.2 %}✔{% endif %}</div>
  <div>{% if option.plan.3 %}✔{% endif %}</div>
</div>
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    相关资源
    最近更新 更多