Django在模板中附加+1

时间:2017-04-15 17:36:03

标签: django modal-dialog

我有模态显示来自ExamFile模型的上传图像,该模型是与考试模型连接的外键。为了使灯箱galerry工作,我需要指定每个examfile图片的幻灯片编号,所以我需要为每张图片追加1(可能在模板中?) 我有这个脚本:

{% for file in exam.examfile_set.all %}


<div class="row">
  <div class="column">
    <img src="{{file.exam_file.url}}" width=60 height="60" 
onclick="openModal();currentSlide(//this is where i need to append +1 for every file in exam.examfile_set.all //)" 
class="hover-shadow cursor">
  </div>
{% endfor %}

<div id="myModal" class="modal">
  <span class="close cursor" onclick="closeModal()">&times;</span>
  <div class="modal-content">
     {% for file in exam.examfile_set.all %}
    <div class="mySlides">
      <div class="numbertext">1 / 4</div>
      <img src="{{file.exam_file.url}}" style="width:100%">
    </div>



    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>

    <div class="caption-container">
      <p id="caption"></p>
    </div>
</div>
</div>
</div>
<script>
function openModal() {
  document.getElementById('myModal').style.display = "block";
}

function closeModal() {
  document.getElementById('myModal').style.display = "none";
}

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  var captionText = document.getElementById("caption");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  captionText.innerHTML = dots[slideIndex-1].alt;
}
</script>



{% endfor %}

我发布了完整的代码,但我的问题是在第5行中。提前谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用内置forloop.counter变量:

{% for file in exam.examfile_set.all %}
    <div class="row">
      <div class="column">
        <img src="{{ file.exam_file.url }}" width=60 height="60" 
    onclick="openModal();currentSlide({{ forloop.counter }})" 
    class="hover-shadow cursor">
      </div>
{% endfor %}

文档中的更多信息:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for