2017-07-25 87 views
0

視圖將元素列表傳遞給模板,例如電影列表,並將它們呈現在表格中。每個元素都有其細節,一個特定元素有一個列表。這份清單的內容我想把它們放在一個模式中。我這樣做有兩個for循環如下:將數據傳遞到引導模態Django模板

<table> 
    <thead> 
    <tr> 
     <td>title</td> 
     <td>description</td> 
     <td>hours</td> 
    </tr> 
    </thead> 
    <tbody> 
    {% for key in movies %} 
    <tr> 
     <td>{{ key.title }}</td> 
     <td>{{ key.description }}</td> 
     <td> 
      <!--This button calls my modal--> 
      {% for hour in key.hours %} 
      <li>{{ hour }}</li> 
      {% endfor %} 
      <button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal"></button> 
     </td> 
    </tr> 
    {% endfor %} 
    </tbody> 
</table> 

我的模式是在我的表外我的表格包裝我的表格div。 我想將第二個循環的值傳遞給我的模態。當用戶點擊按鈕時,數值出現在模態內。

我該怎麼做?

回答

1

你有兩個選擇

  1. 您可以使用JavaScript來改變模式的內容,單擊該按鈕時。

  2. 而不是一個模式,你創建一個模式爲每個電影的小時。根據您點擊哪個按鈕,打開不同的模式。

1

正如@jastr所說,有兩種解決方案。其中之一就是做這樣的事情:

  • <ul>
  • 包裝你<li>要素類添加到您的按鈕,例如open-modal
  • 添加點擊監聽到你的按鈕,當用戶點擊 按鈕,添加列表到您的模態

首先,在你的HTML一些變化:

<table> 
    <thead> 
    <tr> 
     <td>title</td> 
     <td>description</td> 
     <td>hours</td> 
    </tr> 
    </thead> 
    <tbody> 
    {% for key in movies %} 
    <tr> 
     <td>{{ key.title }}</td> 
     <td>{{ key.description }}</td> 
     <td> 
      <!-- You may want to put this whole list into your modal body --> 
      <ul> 
      {% for hour in key.hours %} 
      <li>{{ hour }}</li> 
      {% endfor %} 
      </ul> 
      <button type="button" class="btn btn-default open-modal" data-toggle="modal" data-target="#myModal"></button> 
     </td> 
    </tr> 
    {% endfor %} 
    </tbody> 
</table> 

然後,你可以添加一個像這樣的點擊監聽器來將列表插入到你的模態中:

<script type="text/javascript"> 
    $('.open-modal').click(function (e) { 
     $('#myModal .modal-body').html($(this).prev().clone()); 
    }); 
</script>