Miller
Miller

Reputation: 145

Passing a django variable to javascript

I want to pass a django variable which is a dictionary like this {u'testvar1': u'1', u'testvar2': u'38', u'testvar3': u'160'} to javascript.How can I do this?I cant seem to find a solution for the same.I am new to django so sorry for this noobie question.

Upvotes: 1

Views: 78

Answers (4)

chirag soni
chirag soni

Reputation: 1026

First take that dictionary in Django template and set it to the value of one of the html elements like this:

<input type="hidden" id="dict" value="{{your dict}}">

Now take value of html element in javascript.

In java script:
<script>
var dict = document.getElementById("dict").value;

</script>

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599956

First, the fact that you have strings beginning with u means you are using Python 2.7, which is not only an extremely old version of Python but also means you are using outdated versions of Django, as more recent versions only support Python 3. You should upgrade both immediately.

To answer your question though, you should use JSON for this.

return render(request, 'my_template.html', {'data': json.dumps(data)}

and in your template:

var data = JSON.parse("{{ data|safe }}")

Upvotes: 2

JPG
JPG

Reputation: 88649

def foo_view(request, slug):
    context_data = {u'testvar1': u'1', u'testvar2': u'38', u'testvar3': u'160'}
    return render(request, 'foo_template.html', context_data)

#foo_template.html
<script type="text/javascript">
   var a = "{{testvar1}}";
</script>

Upvotes: 0

HenryM
HenryM

Reputation: 5793

You pass the variables via the context and then can use them in your script in the django template

def myview():
    ...
    return render(request, 'my_template.html', {'testvar1': testvar1}


<script>
    var testvar1 = {{ testvar1 }}
</script>

Upvotes: 0

Related Questions