2015-09-29 53 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