.items在Django模板中不能用于defaultdict

时间:2015-09-27 22:27:26

标签: python django dictionary django-templates

我无法在我的Django模板中使用.items:

从我的CBV< get_context_data:

复制并粘贴
var results = ( function() {
    var currentPlayer = "X"
    var b = new Array(9) // Assumed 'b' was array of played moves

    // "$box" - make sure this one is available by this point
    // or just set it accordingly. 
    $box.on( "click", function(e) {
        var index = e.target.dataset.index;

        // make sure the current index was never played
        if ( index === undefined ) {
           if ( currentPlayer === "X" ) {
               b[index] = "X"
               currentPlayer = "O"
           }
            else {
               b[index] = "O"
               currentPlayer = "X"
            }
        }
    } )

    // Return a reference to the array which holds each squre value 
    return b;
} () )

从我的模板中复制并粘贴:

    context['data'] = assertion_dict
    context['dataitems'] = assertion_dict.items()

    return context

输出:

  <h3>data dump</h3>
  {{data}}

  <h3>dataitems</h3>
  {% for key, value in dataitems %}
     {{ key }}: {{ value }} <br/>
  {% endfor %}

  <h3>data.items</h3>
  {% for key, value in data.items %}
     {{ key }}: {{ value }} <br/>
  {% endfor %}

  <h3>Not found test</h3>
  {{ i_dont_exist }}

为什么第二个版本没有工作,我在模板中使用data.items?

1 个答案:

答案 0 :(得分:5)

这是known issue in Django:您无法在模板中迭代var bottomLine = CALayer() bottomLine.frame = CGRectMake(0.0, 75 - 1, 300, 1.0) bottomLine.backgroundColor = UIColor.whiteColor().CGColor myTextField.borderStyle = UITextBorderStyle.None myTextField.layer.addSublayer(bottomLine) 。文档建议to handle this的最佳方式是将defaultdict转换为defaultdict,然后再将其传递给模板:

dict

顺便说一下,它不起作用的原因是,当您在模板中调用context['data'] = dict(assertion_dict) 时,Django将首先尝试查找{{ data.items }},然后data['items']data.items将返回前者的默认值,因此Django不会尝试后者,并且您最终会尝试循环使用默认值而不是dict。