{%for%}中的Django模板变量循环到Javascript中 [英] Django template variables from {% for %} loop into Javascript

查看:371
本文介绍了{%for%}中的Django模板变量循环到Javascript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是遍历记录的Django模板。每个记录都包含一个JS函数填充的div。为了使JS知道要做什么,它需要从每个for循环迭代中获取一个变量并使用它。我不知道该如何实现或是否有可能。我不知道在记录是否在单独的JS对象实例中触发计时器的情况下,可能需要一种不同的方法。

This is a Django template iterating through records. Each record contains a div that JS function fills in. In order for JS to know what to do, it needs to get a variable from each for loop iteration and use it. I don't know exactly how to achieve that or if it's possible. Maybe a different approach is needed where ever record triggers a timer in a separate JS object instance, I don't know.

---------- html -----------------------

---------- html -----------------------

{% for match in upcoming_matches %}
...

<tr>
<td> Match title </td>
<td> Match time </td>
<td> Starts in: </td>
<tr>

<tr>
<td> {{ match.title }} </td>
<td> {{ match.start_time }} </td>
<td> <div id="matchCountdown"/></td>
<tr>

...

{% endfor %}

------------ JS ---------------------------

------------ JS ---------------------------

$(function () {

        var start_date = {{ match.start_date }}; // Obviously I can't access vars from for loop, I could access upcoming_matches but not the ones from for loop


        var matchDate = new Date(start_date.getTime() 

     $('#matchCountdown').countdown({until: matchDate});

    });


推荐答案

您可以将start_date输出为matchCountdown的属性。然后在您的JavaScript中将其选中,进行处理并使用Countdown插件输出。

You could output the start_date as an attribute of the matchCountdown . Then in your JavaScript pick it out, process it and output with the Countdown plugin.

模板代码:< td>< div class = matchCountdown start = {{match.start_date}} />< / td>

JavaScript:

JavaScript:

$('.matchCountdown').each(function() {
    this = $(this);
    var start_date = this.attr('start');
    var matchDate = new Date(start_date).getTime();
    this.countdown({until: matchDate});
});

此方法只需要在模板代码中执行一个循环,在Javscript中执行一个循环即可查找并启用项目。还要注意, matchCountdown应该是div的 class 而不是 id ,因为它不是唯一的。

This method requires only one loop in the template code and one loop in the Javscript to find and enable the items. Also of note, 'matchCountdown' should be a class not an id of the div since it's not unique.

这篇关于{%for%}中的Django模板变量循环到Javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆