Quickly, getting a table of records

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

    {{=rows}}
    

    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:}}
    <tr> 
    <td>{{row.title}} </td>
    <td>{{row.location}} </td>
    </tr>
    {{pass}}
    </table>
    

    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>
    {{pass}}
    {{for r in records:}}
    <tr>{{for k,v in r.items():}}
    <td>{{=v}}</td>
    {{pass}}</tr>
    {{pass}}
    </table>
    {{return}}
    
  • 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

    2 Responses to Quickly, getting a table of records

    1. SyBiR says:

      Thank you very much for this post.
      Your examples helped me a lot.

    2. if you need to see data from table, you shoud write {{=row.title}} but not {{row.title}}

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s

    %d bloggers like this: