pynovice
pynovice

Reputation: 7752

How to use following python dictionary in template using javascript?

I have a Python dictionary like this:

{'test_data': ['reads_1.fq', 'reads_2.fq'], 'test_data/new_directory': ['ok.txt'], 'hello': ['ok.txt'], 'hello/hi/hey': ['b.txt']}

I want to use this in the template(Django) to create a tree structure like:

test_data
 reads_1.fq
 reads_2.fq

test_data/new_directory
 ok.txt

hello
 ok.txt

hello/hi/hey
 b.txt

How can this be done using javascript? Thanks

Upvotes: 0

Views: 198

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53981

Convert the dictionary to json first in your view and use javascript to work directly on the json (instead of using django's template language to try and format javascript)

# In your view somewhere
import json

def my_view(request):
    ...
    return render_to_response('my_template.html',{ 'my_json': json.dumps(my_dict) }, context_instance=RequestContext(request))

and in your template:

<script>
     obj = {{ my_json|safe }};
     for (var prop in obj){  // Iterating through an object
         console.log(prop);
         for(i=0, i < obj[prop].length, i++){  // Iterating through the list for each key
              console.log(obj[prop][i]);
         }
     }
</script>

Upvotes: 2

Related Questions