Search code examples
pythonhtmlweb-applicationswebpyramid

How to display an array of objects in page template in Pyramid?


I have a small simple question in HTML+Pyramid.

Consider I have one table in database and I want to display all records from this table in my page template. I know how to retrieve the data from database, but I don't know how to display them on HTML page. I know how to show one single value, for instance total number of records in a table. I can return a simple JSON on my callable view and render it. Like here:

@view_config(route_name='tasks', renderer='templates/tasks.pt')
def view_tasks(request):
    try:
        count = DBSession.query(MyTable).all().count()
    except DBAPIError:
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
    return { 'Total' : count }

And corresponding HTML code:

...
<h3>Now ${Total} tasks are not completed</h3>
...

But how do I return a set of records? Or how do I show them on HTML page another way? Any suggestions?

@view_config(route_name='tasks', renderer='templates/tasks.pt')
def view_tasks(request):
    try:
        items = DBSession.query(Task).all() # this is a set of objects
    except DBAPIError:
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
    return { # how to display them on page tamplate??? }

Solution

  • You're using Chameleon (the .pt extension), so you'll get a lot of mileage out of reading their documentation.

    <table>
      <tr tal:repeat="item items">
        <td>${item.name}</td>
        <td>${item.description}</td>
      </tr>
    </table>