0

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.

mursalin
1,1811 gold badge7 silver badges18 bronze badges
asked Jun 30, 2020 at 12:57

2 Answers 2

1

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.

answered Jun 30, 2020 at 14:31
Sign up to request clarification or add additional context in comments.

Comments

0

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) }
answered Aug 25, 2022 at 5:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.