2

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 :(

4
  • How is your Javascript supposed to know what 'user_a' is? Commented Jul 7, 2012 at 20:50
  • @DanielRoseman I didn't got you. I just checked these error with the Fire bug or Inspected element tools in Chrome Commented Jul 7, 2012 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. Commented Jul 7, 2012 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? Commented Jul 7, 2012 at 23:32

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.