0

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. :)

Sreeram
  • 3
  • 1

1 Answers1

0

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.
Steve Piercy
  • 13,693
  • 1
  • 44
  • 57
  • Thanks for your help.. Actually I solved this one. I used Jinja2 templating to get off this problem. There is a looping structure (like for loop) by which you can directly access python objects and iterate them. [link](http://jinja.pocoo.org/docs/dev/templates/) – Sreeram Jul 12 '16 at 11:55
  • @Sreeram: Not that Chameleon didn't have any ways to iterate over a Python list :) – Sergey Jul 12 '16 at 20:13
  • It would be helpful if you could tell me how I can do that. Thanks :) @Sergey – Sreeram Jul 13 '16 at 11:38
  • @Sreeram: tal:repeat is your friend: https://chameleon.readthedocs.io/en/latest/#introduction – Sergey Jul 13 '16 at 19:35