- TurboGears 教程
- TurboGears - 首頁
- TurboGears - 概述
- TurboGears - 環境
- TurboGears - 第一個程式
- TurboGears - 依賴項
- TurboGears - 服務模板
- TurboGears - HTTP 方法
- Genshi 模板語言
- TurboGears - 包含
- TurboGears - JSON 渲染
- TurboGears - URL 層次結構
- TurboGears - Toscawidgets 表單
- TurboGears - 驗證
- TurboGears - 快閃記憶體訊息
- TurboGears - Cookie 和會話
- TurboGears - 快取
- TurboGears - Sqlalchemy
- TurboGears - 建立模型
- TurboGears - CRUD 操作
- TurboGears - 資料網格
- TurboGears - 分頁
- TurboGears - 管理員訪問
- 授權與認證
- TurboGears - 使用 MongoDB
- TurboGears - 腳手架
- TurboGears - 鉤子
- TurboGears - 編寫擴充套件
- TurboGears - 可插拔應用程式
- TurboGears - RESTful 應用程式
- TurboGears - 部署
- TurboGears 有用資源
- TurboGears - 快速指南
- TurboGears - 有用資源
- TurboGears - 討論
TurboGears – 分頁
TurboGears 提供了一個方便的裝飾器,稱為 paginate(),用於將輸出分成多個頁面。此裝飾器與 expose() 裝飾器結合使用。@Paginate() 裝飾器將查詢結果的字典物件作為引數。此外,每頁記錄的數量由 items_per_page 屬性的值決定。確保將 paginate 函式從 tg.decorators 匯入到您的程式碼中。
如下重寫 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)
每頁專案設定為三個。
在 studentlist.html 模板中,透過在 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>
在瀏覽器中輸入 **https://:8080/listrec**。將顯示錶格中第一頁的記錄。在此表格頂部,還可以看到頁面編號的連結。
如何向資料網格新增分頁支援
還可以向資料網格新增分頁支援。在以下示例中,分頁資料網格旨在顯示操作按鈕。為了啟用操作按鈕,資料網格物件使用以下程式碼構建:
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)
瀏覽器顯示分頁資料網格如下所示:
點選第三行中的“編輯”按鈕,它將重定向到以下 URL **https://:8080/edit?name=Rajesh+Patil**
廣告