0

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

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

4 Comments

When I see the data: the data looks like: ata = {&quot;test_data&quot;: [&quot;reads_1.fq&quot;, &quot;reads_2.fq&quot;], &quot;test_data/new_directory&quot;
I forgot to add that you need to mark the template variables output as being safe. I've updated the answer.
Hm. No error is shown. Variable is passed to template too. But I can't see any outputs on the console.
I've updated the code but it's untested; you'll need to work on the javascript yourself and debug why or why it isn't working. Use the console.log to make sure data is properly populated. From there it's a simple case of looping through the object and printing it how you like.

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.