Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a python-Django list:

list_a = ['user_a', 'user_b']

Now i render it to a template with the following code:

extra_context = {
    'a': list_a
}
return direct_to_template(request, 'mytemplate.html', extra_context)

In my template, I wrote the following java script code to pass the list_a Django-list to Js-list:

var user = [{% for i in user_list %}{{ i }}{% if forloop.last %}{%else%},{%endif%}{% endfor %}];

But when i open the template. It is showing following error (checked with Inspect element):

Uncaught ReferenceError : user_a is not defined

I tried to print the user variable reside in javascript using Inspect Element. It print the correct value i.e.

var user = [user_a, user_b]

I am not able to understand why is it happening :(

share|improve this question
How is your Javascript supposed to know what 'user_a' is? – Daniel Roseman Jul 7 '12 at 20:50
@DanielRoseman I didn't got you. I just checked these error with the Fire bug or Inspected element tools in Chrome – Amit Pal Jul 7 '12 at 23:10
@AmitPal right, so var user = [user_a, user_b], but what are user_a and user_b? Those inner names are not defined, hence the error. – kojiro Jul 7 '12 at 23:26
@kojiro OH!I got that, But how should i defied that because it is dynamic list fetched from the database in python. I am newbie in Javascript. What should i do? Would it be possible to pass these as a string? – Amit Pal Jul 7 '12 at 23:32

2 Answers

In your template you can use

var user = {{user_list|safe}};

Using this template code, a python list defined as

user_list = ['te"s\'t1', 'test2'];

gives the following results when viewing javascript source

var user = ['te"s\'t1', 'test2'];

Whereas your original solution will give

var user = ["te"s't1","test2"];

Which one you use really depends on what you intend to do with the usernames. Regardless of whether you use 'safe' or not in your template, it seems like the for and if statements in your template are a bit over-worked.

share|improve this answer
up vote 0 down vote accepted

I think that i have found the mistake:

Update `var user = [{% for i in user_list %}{{ i }}{% if forloop.last %}{%else%},{%endif%}{% endfor %}];

to

var user = [{% for i in user_list %}"{{ i }}"{% if forloop.last %}{%else%},{%endif%}{% endfor %}];`

are giving me the right solution.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.