{%for%}中的Django模板变量循环到Javascript中

Ska*_*Ska 3 javascript django django-templates

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

---------- 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 %}
Run Code Online (Sandbox Code Playgroud)

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

    });
Run Code Online (Sandbox Code Playgroud)

Der*_*wok 6

您还可以在代码的 javascript 部分使用 {% for %} 循环。如果你在你的 html 模板中写这个:

<script type="text/javascript">
    $(function() {
        {% for match in upcoming_matches %}
            var match_date_{{ match.id }} = new Date({{ match.start_date }}).getTime();
            $('#matchCountdown_{{ match.id }}').countdown({until: match_date_{{ match.id }});
        {% endfor %}
    });
</script>
Run Code Online (Sandbox Code Playgroud)

此外,在这种情况下<div id="matchCountdown"/>成为<div id="matchCountdown_{{ match.id }}"/>


JCo*_*ton 5

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

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

JavaScript:

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

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