0

i`m creating a slider so i want to get an element of template array in Django. my HTML file is:

<div id="sideBar_mostVisited_control">
    <a href="">
        <p>
            {{ mostVisited_names.0 }}
        </p>
    </a>
    <div>
        <p>
            1
        </p>
    </div>
    <button type="button" id="mostVisited_arrowRight">
        <img src="{% static 'icons/base/arrowRight.png' %}" id="mostVisited_arrowRight">
    </button>
    <button type="button" id="mostVisited_arrowLeft">
        <img src="{% static 'icons/base/arrowLeft.png' %}" id="mostVisited_arrowLeft">
    </button>
</div>
<div id="sideBar_mostVisited_images">
    <div>
        {% for image in mostVisited_images %}
            <img src="{{ image }}">
        {% endfor %}
    </div>
</div>

i want to change name when its image changed. my jQuery file is:

var index=$('#sideBar_mostVisited_control div p').html();
$('#sideBar_mostVisited_control div p').html(index+1);
$('#sideBar_mostVisited_control a p').html("{{ mostVisited_names.index }}");

but index is not recognized in {{ mostVisited_names.index }}. what can i do?

hamid
  • 694
  • 1
  • 8
  • 20
  • Possible duplicate of [How can I pass my context variables to a javascript file in Django?](http://stackoverflow.com/questions/8683922/how-can-i-pass-my-context-variables-to-a-javascript-file-in-django) – rnevius Mar 23 '16 at 13:23
  • Also: http://stackoverflow.com/questions/298772/django-template-variables-and-javascript/1187881#1187881 – rnevius Mar 23 '16 at 13:25
  • i can get a single variable in inline js but i can not get an element of passed array. – hamid Mar 23 '16 at 19:11

1 Answers1

0

The problem :

Since the JS file is static, you can't put Django variables into it.

A solution :

A way to resolve this situation is to "store" Django variables needed for your js in your html. Afterward you can grab it and use it in your js script !

Some code :

<script type="text/javascript">
  // "store" variables from Django in the body
  $('body').data('name_index', {{mostVisited_names.index}});
</script>

Then in your JS, get the value from the datamap:

var index=$('#sideBar_mostVisited_control div p').html();
$('#sideBar_mostVisited_control div p').html(index+1);
$('#sideBar_mostVisited_control a p').html($('body').data('name_index'));
1ronmat
  • 1,147
  • 8
  • 15
  • in this case index is not a js variable, i want to use js variables in {{ , }} but i can`t. i have tried filters in django but in this case i must pass variables in {{ , }} too, so i can`t use js variables in it. – hamid Mar 24 '16 at 14:18