0

我有一个这样的 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 来做到这一点?谢谢

4

1 回答 1

2

在你的视图中首先将字典转换为 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>
于 2013-06-17T10:22:37.077 回答