Quickly, getting a table of records

April 28, 2010
  • Of course you know that something like:
    rows = db(db.jobs.id > 0).slect()

    yields a Rows object that can be returned using :

    return dict(rows=rows)

    and in your view making something like:


    will get you a table , yes an HTML table created for you on the fly

  • The problem with this approach is that when you need more customization like decorating your table using java script or doing any other customization you’ll have to create the table manually in the view doing something like:
    <table class="blahblahblah">
    <th> {{T("Title'')}} </th>
    <th> {{T("Location'')}} </th>
    {{for row in rows:}}
    <td>{{row.title}} </td>
    <td>{{row.location}} </td>

    boring is not it ?

  • We can make another hackish trick which makes our lives easier:
    since Rows object has an attribute called colnames containing the column names of the rows being returned and since column names consists of table_name.field_name:
    you can do something like :

    x = db(db.jobs.id>0).select()
    [column.split('.')[1] for column in x.colnames]
    ['id', 'title']

    Now you can do :

    ---- mytable.html ----
    {{def mytable(records, class_name=''):}}
    <table class="{{=class_name}}">
    {{for col in [column.split('.')[1] for column in x.colnames]:}}
    <th> col</th>
    {{for r in records:}}
    <tr>{{for k,v in r.items():}}
  • After that all you need to do when ever trying to make a table is to
    import mytable.html in your view with

     {{include 'mytable.html'}}

    and use it

    {{mytable(db(...).select(), 'class_name')}}

    then you can personalize your table as you want and reuse it.

  • Advertisements