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**。將顯示錶格中第一頁的記錄。在此表格頂部,還可以看到頁面編號的連結。

Record

如何向資料網格新增分頁支援

還可以向資料網格新增分頁支援。在以下示例中,分頁資料網格旨在顯示操作按鈕。為了啟用操作按鈕,資料網格物件使用以下程式碼構建:

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)

瀏覽器顯示分頁資料網格如下所示:

Registration Form

點選第三行中的“編輯”按鈕,它將重定向到以下 URL **https://:8080/edit?name=Rajesh+Patil**

廣告