javascripttemplatespyramidnameerrorchameleon

Name error while using chameleon templating in Pyramid framework


I found this error while trying to run javascript in chameleon template, with pyramid framework.

This is the code that fetches data from the sqlite database.

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

The chameleon template file testpage.pt goes like this,

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

Error page shows up saying Name error:i

 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>

Thanks for any help. :)


Solution

  • That's a Python error. In the Chameleon template testpage.pt you use syntax that Chameleon (and so Python) will parse as noted by the error.

    To avoid the issue, you have at least two options.

    1. Move the inline javascript to an external file, serving it as a static asset, and replace the inline with a reference to the external file.
    2. Escape the JavaScript syntax so that Chameleon does not parse it as Python.