0

Here is my problem. PictureLenth is my picture array length, and ProductImage is a list. I can't use now to point my array address on ProductImage. How can I use javascript var on {{}}?

lenth = {{ PictureLenth }}-1;
now = 0;

function t_setInterval() {
window.intervalParam = window.setInterval(function() {
var date = new Date();
   if (lenth>now)
   {now = now + 1;}
   else
   {now = 0;}
    var img = document.getElementById("image");
    img.src="data:image/png;base64, {{ ProductImage[now] }}";
    return false;
}, 4000);
}
Alex K
  • 8,269
  • 9
  • 39
  • 57
Frank Liao
  • 855
  • 1
  • 8
  • 25

2 Answers2

1

This is because Jinja doesn't have any access to now when it runs on the server side and when the JavaScript runs on the client side the string is static and will never change. The solution is to provide ProductImage as a JavaScript variable using Flask's tojson filter:

var images = {{ ProductImage | tojson | safe }},
    length = images.length - 1,
    now = 0;

function t_setInterval() {
  window.intervalParam = window.setInterval(function() {
    if (length > now) now = now + 1;
    else now = 0;
    var img = document.getElementById("image");
    img.src = "data:image/png;base64, " + images[now];
    return false;
  }, 4000);
}
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
0
lenth = {{ PictureLenth }}-1;
now = 0;

function t_setInterval() {
window.intervalParam = window.setInterval(function() {
var date = new Date();
   if (lenth>now)
   {now = now + 1;}
   else
   {now = 0;}
    var ProductImage = {{ProductImage|safe}};
    var img = document.getElementById("image");
    img.src="data:image/png;base64,"+ProductImage[now];
    return false;
}, 4000);
}
Jey
  • 118
  • 6