2015-12-12 79 views
0

我一直在嘗試將變量傳遞給{{list}},但我似乎無法找到方法。有沒有一個正確的方法來做到這一點與Javascript?或者Javascript和Jinja不能交流?有沒有辦法用javascript變量來索引Django/Jinja列表?

我需要序列化我的模型,並將它傳遞給一個JavaScript變量?

+0

請問您可以添加您的代碼嗎? –

回答

1

有很多方法可以做。

1.第一種方式是在jinja2渲染時間手動定義變量。

如果Python代碼是:

def sample(request): 
    return render(request, 
        'sample_template.html', 
        { 
         'data': [1, 2, 3, 4, 5], 
        }) 

sample_template.html是:

<html> 
    <head><title>sample</title></head> 
    <body> 
     <script> 
     var data = "{{ data }}"; 
     // and now, you can parse value of data variable. And then using it. 
     </script> 
    </body> 
</html> 

2.定義另一個端點用於獲取數據(創建API)

蟒:

from django.http import JsonResponse 

def sample(request): 
    return render(request, 'sample_template.html') 

def api(request): 
    return JsonResponse({'data': [1, 2, 3, 4, 5]}) 

html:

<html> 
    <head> 
     <title>sample</title> 
     <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> 
    </head> 
    <body> 
     <script> 
     var data; 
     $.ajax({ 
      url: 'endpoint-for-api' 
     }).done(function(d) { 
      data = d; 
     }); 
     // and also you using it. 
     </script> 
    </body> 
</html> 
相關問題