hari prasanth
hari prasanth

Reputation: 746

How to pass Django template variable to JavaScript function

I passed personal information in js file using views.py. So, In the js file, I added the Django template for loop to iterate the personal information and pass the javascript function. but it's not working for me. I am new in this concept.

View file

def sample(request):
    p=[]
    p.append({name:santhosh, age:20},name:kumar, age:21})
    return render(request, 'index.js',{'p':p})

index.js

{% for i in p %}
    var data = load_html(i)
{% endfor %}

function load_html(i){
    return '<h1>{{ i.name }}</h1>'
}

This is my sample code. I tried to pass (i value in load_html()) function. but it cannot pass the value in that function. How to pass value and get name.

Upvotes: 0

Views: 2526

Answers (2)

DragonFire
DragonFire

Reputation: 4082

Do the follwing, notice in the template the use of single quotes while passing function variable.

In Template

 <a href="#" class="some_class" onclick="someFunction('{{ row.item_id }}');">Do Something</a>

In Jquery

function someFunction(item_id) {
    alert(item_id) }

Upvotes: 0

mursalin
mursalin

Reputation: 1181

Your Django template is constructed in server site and javascript is a client side language. So in simple term You can't send Django template variable to javascript function.

however there is a workaround. You can add your Django variable value as attribute. like for example

<span id='elId' userName="{{p.name}}" userAge="{{p.age}}"></span>

and in your script section with jQuery or js you can get those attribute value and use as per requirements.

var $x = $("#elId");
alert($x.attr("userName"));

its not pretty, but it works.

Upvotes: 1

Related Questions