javascript - Python Flask 模板使用 {{}} 不能混合 javascript var

标签 javascript python templates flask jinja2

这是我的问题。 PictureLenth是我的图片数组长度,ProductImage是一个列表。我现在无法使用在 ProductImage 上指向我的数组地址。如何在 {{}} 上使用 javascript var?

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);
}

最佳答案

这是因为 Jinja 在服务器端运行时无法访问 now,而当 JavaScript 在客户端运行时,字符串是静态的并且永远不会改变。解决方案是使用 Flask's tojson filterProductImage 作为 JavaScript 变量提供。 :

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);
}

关于javascript - Python Flask 模板使用 {{}} 不能混合 javascript var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27538840/

相关文章:

javascript - 以功能方式交换两个数组元素

javascript - Facebook Graph API 2.2 共同好友

python - 在 for 循环中绘图,在 matplotlib 中具有 'hold on' 效果?

c++ - Typedef Student 不工作

javascript - 使用 jQuery 获取超出 Angular 范围的 h4 类 ="ng-binding"的文本内容

javascript - 如何在javascript中使用严格模式发送控制字符?

python - 为什么 10 次方不等于 Python 中大数的科学记数法?

python - 类型错误 : at/ 'module' object is not callable

c++ - 为什么为 T 推导的类型是 const int in void func(T const &t)

c++ - 自动模板参数、数据成员和常量