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.

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.

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) }

Comments

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.