如何在模板中使用以下python字典

How to use following python dictionary in template using javascript?

本文关键字:python 字典      更新时间:2023-09-26

我有一个这样的Python字典:

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

我想在模板(Django)中使用它来创建一个树结构,如:

test_data
 reads_1.fq
 reads_2.fq
test_data/new_directory
 ok.txt
hello
 ok.txt
hello/hi/hey
 b.txt

如何使用javascript做到这一点?由于

首先在视图中将字典转换为json,然后使用javascript直接处理json(而不是使用django的模板语言来尝试格式化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))

和在你的模板中:

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