如何在Django模板中遍历字典?

时间:2019-02-20 21:45:55

标签: javascript python django python-3.x django-templates

我正在尝试遍历django模板中的字典并将值保存到window.obj,但是它不起作用。

views.py:

def myView(req):
...
myDict = {'foo':"[1,2]", 'bar':"[3,4]"} 

return render(req, 'myPage.html', {'myDict':myDict})

myPage.html:

<script type="text/javascript">
window.obj = {}
window.obj["foo"] = "{{ myDict.foo }}";

{% for key, value in myDict %}

window.obj["{{ key }}"] = "{{ value }}";

{% endfor %}
</script>

...

<script> 
console.log(window.obj.foo); //prints {foo: "[1,2]"} 
console.log(window.obj.bar); //prints undefined
</script>

注意:我不能在实际项目中使用myDict.foo

我在这里想念什么?

1 个答案:

答案 0 :(得分:3)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST">
  <div class="table-responsive">
    <table class="table table-striped table-sm">
      <thead class="thead-dark">
        <tr>
          <th scope="col">Location</th>
          <th scope="col">Serial #</th>
          <th scope="col">Level</th>
          <th scope="col"></th>
          <th scope="col"></th>
          <th scope="col"></th>
        </tr>
      </thead>
      <tbody>
        <tr scope="row">
          <td class="align-middle">East Entrance (Elvis Car)</td>
          <td class="align-middle">CR5E180022B</td>
          <td><input type="number" name="LevelAmount[]" class="unitType form-control" value=""></td>
          <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Image</button></td>
          <td><input type="hidden" class="unitType" name="unitType" value="Sienna 5 B.png"></td>
          <td><input type="hidden" name="id[]" value="S1149"></td>
        </tr>
        <tr scope="row">
          <td class="align-middle">Hotel Elevator Bthrm - Womens</td>
          <td class="align-middle">CS3G170159</td>
          <td><input type="number" name="LevelAmount[]" class="unitType form-control" value=""></td>
          <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Image</button></td>
          <td><input type="hidden" class="unitType" name="unitType" value="Sienna 3.png"></td>
          <td><input type="hidden" name="id[]" value="S1151"></td>
        </tr>
      </tbody>
    </table>
  </div>
  <div class="row">
    <div class="col-12 text-right"><input type="hidden" name="SessionID[]" value="">
      <input class="btn btn-warning" type="submit" name="submit" value="Submit">
    </div>
  </div>