Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    });
like image 922
Ska Avatar asked Sep 23 '11 15:09

Ska


3 Answers

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.

like image 168
Derek Kwok Avatar answered Sep 30 '22 00:09

Derek Kwok


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.

like image 44
JCotton Avatar answered Sep 30 '22 01:09

JCotton


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");
like image 20
Gourneau Avatar answered Sep 30 '22 01:09

Gourneau