Turbogears-pagination
TurboGears –ページネーション
TurboGearsは、ページの出力を分割するpaginate()と呼ばれる便利なデコレーターを提供します。 このデコレータは、expose()デコレータと組み合わされます。 @Paginate()デコレータは、クエリ結果の辞書オブジェクトを引数として受け取ります。 また、ページあたりのレコード数は、items_per_page属性の値によって決定されます。 tg.decoratorsからコードにpaginate関数をインポートしてください。
次のようにroot.pyのlistrec()関数を書き換えます-
from tg.decorators import paginate
class RootController(BaseController):
@expose ("hello.templates.studentlist")
@paginate("entries", items_per_page = 3)
def listrec(self):
entries = DBSession.query(student).all()
return dict(entries = entries)
1ページあたりの項目は3つに設定されています。
studentlistlテンプレートでは、py:forディレクティブの下にtmpl_context.paginators.entries.pager()を追加することにより、ページナビゲーションが有効になります。 このテンプレートのコードは次のようになります-
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:py = "http://genshi.edgewall.org/">
<head>
<link rel = "stylesheet" type = "text/css" media = "screen"
href = "${tg.url('/css/style.css')}"/>
<title>Welcome to TurboGears</title>
</head>
<body>
<h1>Welcome to TurboGears</h1>
<py:with vars = "flash = tg.flash_obj.render('flash', use_js = False)">
<div py:if = "flash" py:replace = "Markup(flash)"/>
</py:with>
<h2>Current Entries</h2>
<table border = '1'>
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Address</th>
<th>Pincode</th>
</tr>
</thead>
<tbody>
<py:for each = "entry in entries">
<tr>
<td>${entry.name}</td>
<td>${entry.city}</td>
<td>${entry.address}</td>
<td>${entry.pincode}</td>
</tr>
</py:for>
<div>${tmpl_context.paginators.entries.pager()}</div>
</tbody>
</table>
</body>
</html>
ブラウザに http://localhost:8080/listrec と入力します。 テーブル内のレコードの最初のページが表示されます。 この表の上部には、ページ番号へのリンクも表示されます。
ページネーションサポートをDatagridに追加する方法
データグリッドにページネーションのサポートを追加することもできます。 次の例では、ページ分割されたデータグリッドはアクションボタンを表示するように設計されています。 アクションボタンをアクティブにするために、データグリッドオブジェクトは次のコードで構築されます-
student_grid = DataGrid(fields = [('Name', 'name'),('City', 'city'),
('Address','address'), ('PINCODE', 'pincode'),
('Action', lambda obj:genshi.Markup('<a
href = "%s">Edit</a>' % url('/edit',
params = dict(name = obj.name)))) ])
ここで、アクションボタンは、データグリッドの各行の名前パラメーターにリンクされています。
次のように* showgrid()*関数を書き直します-
@expose('hello.templates.grid')
@paginate("data", items_per_page = 3)
def showgrid(self):
data = DBSession.query(student).all()
return dict(page = 'grid', grid = student_grid, data = data)
ブラウザには、ページ分割されたデータグリッドが次のように表示されます-
3行目の[編集]ボタンをクリックすると、次のURLにリダイレクトされます http://localhost:8080/edit?name = Rajesh + Patil