2015-09-29 56 views
1

我有一個模板2循環:Django的 - 引導:莫代爾

{% for person in players %} 
    <a href="#" class="thumbnail" data-toggle="modal" data-target="#modal_personn"> {{person.user.username}} </a> 
{% endfor %} 

{% for person in examiners %} 
    <a href="#" class="thumbnail" data-toggle="modal" data-target="#modal_personn"> {{person.user.username}} </a> 
{% endfor %} 

和我在同一模板模式:

<div id="modal_person" class="modal fade" role="dialog"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal">&times;</button> 
       <div> 
        <h3 class="modal-title"> {{person.user.username}} </h3> 
        <i>{{ person.created_at|date:"d M, Y" }}</i> 
       </div> 
      </div> 
      <div class="modal-body"> 
       {% with subscribe = person.user.subscribe %} 
        {% if subscribe.age %} 
         <div> 
          {{subscribe.age }} years old 
         </div> 
        {% endif %} 
        {% if subscribe.presentation %}         
         <h4> His presentation </h4> 
         <div class="row"> 
          {{ subscribe.presentation }} 
         </div> 
        {% endif %} 
       {% endwith %} 
      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn" data-dismiss="modal"> Contact </button> 
      </div> 
     </div> 
    </div> 
</div> 

所以,問題是:我不想在這兩個循環中插入模態,因爲最後它們有很多模態......這是不正確的。

所以我希望當用戶點擊循環中的鏈接時,這種模式將打開特定於循環當前「人員」的數據。

這是怎麼做到的?

我想利用這個(模式的數據-ID):

<a href="#" class="thumbnail" data-toggle="modal" data-target="#modal_personn" data-id="{{person.user}}">{{person.user.username}} </a> 

和模態完成與數據-ID(jQuery的)的值。你怎麼看 ?

什麼是您打開一個模式的解決方案,它包含當前循環中的人的價值?

回答

0

做你問什麼問題的方法是使用像jQuery庫,取決於被點擊鏈接什麼動態改變模式的內容:

$("a.thumbnail").click(function() { 
    var personId = $(this).attr('id'); 
    // Use jQuery to adjust the modal based on the data attributes. 
    // You would still have to pass these attributes to the DOM 
    // somehow, like 
    var age = $(this).attr('age'); 
    $("#modal-person .age").text(age); 
}); 

但是,你說:

所以問題是:我不想在這兩個循環中插入模態,因爲最後它們有很多模態......並且它不合適。

爲每個人製作不同的模式會更簡單 - 沒有什麼內在不適合的。事實上,要實現上述解決方案,如果每次有人點擊模式按鈕時都不使用AJAX,則無論如何都必須將每個人的所有數據都傳遞給數據屬性。爲什麼不只是在for循環中構建所有的各種模塊?

正在DRY的代碼並不是關於具有較少的呈現HTML - 如果您要在for循環中呈現模式,它仍然是DRY代碼。

+0

恐怕最後我的模板包含20個以上的模態!事實上,如果我的第一圈包含10圈,第二圈也是,我的頁面將包含20個模態,因爲在每圈中,模態被創建......(此外,bootstrap-modal使用javascrip,我認爲) – Zoulou

+0

我還沒有確定問題是什麼 - 無論如何你必須傳遞來自服務器的所有數據。即,'subscribe.age','subscribe.presentation',所有這些變量都需要以某種方式訪問​​。您可以將它們作爲'data-attributes'傳遞給您的鏈接,然後使用jQuery,但將這些模式呈現爲HTML會更簡單。 – YPCrumble

+0

那麼,有一個包含很多模塊的模板並不一定用於本質上是不恰當的?由於巫婆我的解決方案(數據ID在模態),該模板只包含一個模式,這種模式完成時,點擊一個循環的鏈接.. – Zoulou