2016-07-11 47 views
0

我試圖在金字塔框架中運行變色龍模板中的javascript時發現此錯誤。在金字塔框架中使用變色龍模板時名稱錯誤

這是從sqlite數據庫中提取數據的代碼。

@view_config(route_name='ddo2', renderer='../templates/pages/testpage.pt') 
def ddo2(request): 
    query = request.dbsession.query(UserRoles) 
    allusers = query.filter(UserRoles.role_id == 1).all() 
    length = len(allusers) 
    return {'all_users':allusers,'length':length} 

變色龍模板文件testpage.pt是這樣的,

<html> 
<body> 
<script type="text/javascript"> 

function createMany(nums){ 

    var str = ""; 

    for(i=0;i<nums;i++){ 

     str += "<input type='radio' name='value1' />${all_users[i].id} <br>"; 

} 

    document.getElementById("divTxt").innerHTML = str; 

} 


</script> 

<p> 



    <input type="button" name="button" id="button" value="To view user details click this" onclick="createMany(${length});" /> 



</p> 

<div id="divTxt"></div> 
</body> 
</html> 

錯誤頁面顯示出來說名稱錯誤:我

NameError: i 

- Expression: "${all_users[i].id} " 
- Filename: c:\nic\pro\scripts\nic\nic\templates\pages\testpage.pt 
- Location: (line 11: col 57) 
    - Source:  ... adio' name='value1' />${all_users[i].id} <br>"; 
              ^^^^^^^^^^^^^^^^^^^^ 
- Arguments: repeat: {...} (0) 
      renderer_name: ../templates/pages/testpage.pt 
      req: <Request - at 0x560e940L> 
      request: <Request - at 0x560e940L> 
      renderer_info: <RendererHelper - at 0x56b53c8L> 
      length: 2 
      context: <instance None at 0x56a9988L> 
      all_users: <list - at 0x56a9e88L> 
      view: <function ddo2 at 0x55d54a8L> 

感謝您的幫助。 :)

回答

0

這是一個Python錯誤。在變色龍模板testpage.pt中,您使用Chameleon(以及Python)將解析的語法,如錯誤所述。

要避免此問題,您至少有兩個選項。

  1. 將嵌入式javascript移動到外部文件,將其用作靜態資源,並將內聯替換爲對外部文件的引用。
  2. 轉義JavaScript語法,使Chameleon不會將其解析爲Python。
+0

感謝您的幫助..其實我解決了這一個。我用Jinja2模板來解決這個問題。有一個循環結構(比如for循環),通過它可以直接訪問python對象並迭代它們。 [鏈接](http://jinja.pocoo.org/docs/dev/templates/) – Sreeram

+0

@Sreeram:不是變色龍沒有任何方法來遍歷Python列表:) – Sergey

+0

這將是有益的,如果你可以告訴我我該如何做到這一點。謝謝:) @Sergey – Sreeram