2015-12-26 13 views
0

我有下面的代碼,我認爲這是作爲後續將數據發送到模板 -如何訪問作爲數組對象的模板中的render_to_response上下文(數據)?

@page_template("app/Discover.html") 
def Discover(request, template="app/Discover.html", extra_context=None):  
    context = {} 
    context['to_loc']=loc_both 
    context['to_av']=av_both 
    context['to_ql']=ql_both  
    if extra_context is not None: 
     context.update(extra_context) 
    return render_to_response(template, context, context_instance=RequestContext(request)) 

在我的模板,我能夠訪問上下文項目如下 -

{% if to_loc %} 
js_loc = {{ to_loc|safe }};  
{% endif %} 
alert('Location is : '+JSON.stringify(js_loc,null,2)); 

{% if to_av %} 
js_av = {{ to_av|safe }};  
{% endif %} 
alert('AV is : '+JSON.stringify(js_av,null,2)); 

這樣上午能夠從上下文訪問單個項目。 但是,有什麼辦法,我可以做如下事情 -

分配上下文對象的JavaScript數組對象,該JavaScript數組包含列表的上下文對象 - >我可以訪問像下面 -

jsonList = []; 
jsonList = contextJSON; // contextJSON holds the context objects that are sent by my view above 
print(JSON.stringify(jsonList.to_loc)); // this should give me the data of locations from respective context object 
print(JSON.stringify(jsonList.to_av)); // this is for for AV 

如何將整個上下文對象分配到js文件中的javascript對象contextJSON中作爲數組?

回答

1

你可以只把你的上下文JSON對象到本身:

@page_template("app/Discover.html") 
def Discover(request, template="app/Discover.html", extra_context=None):  
    context = {} 
    context['to_loc']=loc_both 
    context['to_av']=av_both 
    context['to_ql']=ql_both  
    if extra_context is not None: 
     context.update(extra_context) 
    ctx_copy = context.copy() 
    context['context_json'] = simplejson.dumps(ctx_copy) 
    return render_to_response(template, context, context_instance=RequestContext(request)) 

而且只呈現到你的模板,如JavaScript變量:

jsonList = []; 
jsonList = {{ context_json|safe }}; // contextJSON holds the context objects that are sent by my view above 
print(JSON.stringify(jsonList.to_loc)); // this should give me the data of locations from respective context object 
print(JSON.stringify(jsonList.to_av)); // this is for for AV 
+0

嗨,它拋出錯誤「循環引用檢測」在json.dumps .. –

+0

因此,嘗試新的對象集,併爲其分配上下文,但我無法作爲模板中的數組訪問它。還嘗試刪除json.dumps,你能檢查嗎? –

+0

我向'context dict'添加了一個'copy()'。你需要使用json.dumps()來給這個字典一個json結構。你的模板中的{{context_json}}的輸出是什麼? – RodrigoDela

相關問題