开发者

Django template variables from {% for %} loop into Javascript

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.开发者_JS百科 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 -----------------------

{% 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 ---------------------------

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

    });


You can also use a {% for %} loop in your javascript portion of the code. If you write this in your html template:

<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>

Also, <div id="matchCountdown"/> becomes <div id="matchCountdown_{{ match.id }}"/> in this case.


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.

Template code: <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});
});

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.


Check out jQuery's .data()

Using it you can store data in the DOM like this

<div id="myDiv" data-somedata="myimportantdata"></div>

then you can access it with jQuery like

$("#myDiv").data("somedata");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜