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?

3

1 Answer 1

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'));
Sign up to request clarification or add additional context in comments.

1 Comment

in this case index is not a js variable, i want to use js variables in {{ , }} but i cant. i have tried filters in django but in this case i must pass variables in {{ , }} too, so i cant use js variables in it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.