0

I have been trying to retrieve an Array to my HTML page from my python script(view.py) which looks like this-

def archive(request):
    posts = BlogPost.objects.all()
    myVal = ["Dog Toys", "Dog Bedding", "Dog Feeding", "Health & Hygiene"]
    t = loader.get_template("archive.html")
    c = Context({'myposts' : simplejson.dumps(myVal)})
    return HttpResponse(c)

My JavaScript on test.html looks like this -

<script>
    var results = '{{myposts}}';
    console.log(results);
</script>

The problem I have here is that my array is printed directly on the HTML page meaning my page source has only this -

1 : {'myposts': '["Dog Toys", "Dog Bedding", "Dog Feeding", "Health & Hygiene"]'}

i ams ure there is a way to overcome this, just not sure how to do it, I am working with Python/Django & JavaScript for the first time.

Thanks in advance for the help

shabeer90
  • 5,161
  • 4
  • 47
  • 65
  • 1
    is this helpful ? http://stackoverflow.com/questions/5319896/decode-json-and-iterate-through-items-in-django-template – Ankur Gupta Aug 21 '12 at 10:45
  • @AnkurGupta - To a certain extend yes, thank you, but my console.log(results) prints out a STRING of values ["Dog Toys", "Dog Bedding", "Dog Feeding", "Health & Hygiene"] any idea why its not an Array – shabeer90 Aug 21 '12 at 11:00

3 Answers3

1

Just do

from django.utils.safestring import mark_safe
c = Context({'myposts' : mark_safe(myVal))

And then you need to leave out the quotes to get an array:

var results = {{myposts}};
schacki
  • 9,401
  • 5
  • 29
  • 32
  • I have a "Uncaught SyntaxError: Unexpected token &" and points to ["Dog Toys", "Dog Bedding", "Dog Feeding", "Health & Hygiene"], why does it get converted to special characters in the HTML page? – shabeer90 Aug 21 '12 at 11:10
1

Replace

var results = '{{myposts}}';

with

var results = '{% for post in myposts %} {{ post }}, {% endfor %}';

You generate javascript in html. You can directly transmit list to template:

c = Context({'myposts' : myVal})
Sergei
  • 280
  • 1
  • 10
1

I can add to the Hellpain`s answer next:

var result = "{{myposts|join:'/'}}".split('/');

So firstly python list is joined to the string and then splited by javascript into array

Serhii Holinei
  • 5,758
  • 2
  • 32
  • 46
  • This works perfectly for me, thanks alot, but i have a tiny problem one of my values look like this "Health & Hygiene" how can i make it look like "Health & Hygiene" – shabeer90 Aug 21 '12 at 11:21
  • Try mark string as safe: `var result = "{{myposts|join:'/'|safe}}".split('/');` – Serhii Holinei Aug 21 '12 at 11:32
  • 1
    Marking string as safe in a view.py works for me: `myVal = ["Dog Toys", "Dog Bedding", "Dog Feeding", mark_safe("Health & Hygiene")]` . Import `make_safe` as `from django.utils.safestring import mark_safe` – Serhii Holinei Aug 21 '12 at 11:40