Django For-Loop和Div ID

时间:2016-01-14 18:10:33

标签: jquery django twitter-bootstrap django-templates

我正试图循环一个投资组合,但遇到了障碍。我正在使用Bootstrap,并希望使用Modal灯箱作为图像。我有一个循环通过div的问题,这将允许我的灯箱有一个absolute_url。当我循环浏览网址时正在改变但是当你点击图像来调出灯箱时,它只会因为div id而拉出第一个div。我不是一个java或jquery的家伙,只知道django和python并难倒。

的index.html

    <section id="three" class="no-padding">
    <div class="container-fluid">
        <div class="row no-gutter">
        {% for sites in portfolio %}
            <div class="col-lg-4 col-sm-6">
                <a href="#galleryModal" class="gallery-box" data-toggle="modal" data-src="{{sites.image.url}}">
                    <img src="{{sites.image.url}}" class="img-responsive" alt="Image 1">
                    <div class="gallery-box-caption">
                        <div class="gallery-box-content">
                            <div>
                                <i class="icon-lg ion-ios-search"></i>
                            </div>
                        </div>
                    </div>
                </a>
            </div>
            <div id="galleryModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-body">
                        <img src="//placehold.it/1200x700/222?text=..." id="galleryImage" class="img-responsive" />
                        <p>
                            <br/>
                            <a href="{{ sites.get_absolute_url }}"><button class="btn btn-primary btn-lg" aria-hidden="true">View Details <i class="ion-document"></i></button></a>
                            <button class="btn btn-primary btn-lg" data-dismiss="modal" aria-hidden="true">Close <i class="ion-android-close"></i></button>
                        </p>
                    </div>
                </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
</section>

views.py

def home(request):
about = About.objects.latest('timestamp')
concepts = Concept.objects.order_by('?')[:3]
portfolio = Portfolio.objects.all()[:6]
template = "index.html"
context = {
    "about": about,
    "concepts": concepts,
    "portfolio": portfolio,
}
return render(request, template, context)

JS

$('#galleryModal').on('show.bs.modal', function (e) {
   $('#galleryImage').attr("src",$(e.relatedTarget).data("src"));
});

1 个答案:

答案 0 :(得分:1)

尝试将{{ forloop.counter }}添加到您的ID属性中:

<div id="galleryModal_{{ forloop.counter }}" ...> id="galleryImage" 

<a href="#galleryModal" ...>
<img src="..." id="galleryImage_{{forloop.counter}}" ..>

然后每个块的js:

$('#galleryModal_1').on('show.bs.modal', function (e) {   $('#galleryImage_1').attr("src",$(e.relatedTarget).data("src"));

});

请参阅documentation了解forloop.counter