主頁(yè) > 知識(shí)庫(kù) > Laravel5.5 手動(dòng)分頁(yè)和自定義分頁(yè)樣式的簡(jiǎn)單實(shí)現(xiàn)

Laravel5.5 手動(dòng)分頁(yè)和自定義分頁(yè)樣式的簡(jiǎn)單實(shí)現(xiàn)

熱門(mén)標(biāo)簽:福泉電話機(jī)器人 天津營(yíng)銷(xiāo)電話機(jī)器人加盟代理 地圖標(biāo)注入哪個(gè)科目 南寧crm外呼系統(tǒng)平臺(tái) 太原極信防封電銷(xiāo)卡 熱線電話機(jī)器人 事業(yè)單位如何百度地圖標(biāo)注 電銷(xiāo)招聘機(jī)器人 格陵蘭島地圖標(biāo)注

基于Laravel5.5 在項(xiàng)目實(shí)施過(guò)程中,需要對(duì)從接口中獲取的數(shù)據(jù)(或者通過(guò)搜索工具查詢(xún)出來(lái)的數(shù)據(jù))進(jìn)行分頁(yè)

一、創(chuàng)建手動(dòng)分頁(yè)

在laravel自帶的分頁(yè)中,一般是通過(guò)數(shù)據(jù)庫(kù)查詢(xún)?cè)L問(wèn)paginate()方法來(lái)達(dá)到分頁(yè)的效果 ,like this:

class IndexControllerextends Controller

{  
  publicfunctionindex()
  {
    $person = DB::table('person')->paginate(15);
 
    return view('index.pagTest',['person'=> $person]);
  }
}

查看框架的分頁(yè)源代碼

#vender/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php

/**
   * Paginate the given query.
   *
   * @param int $perPage
   * @param array $columns
   * @param string $pageName
   * @param int|null $page
   * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
   *
   * @throws \InvalidArgumentException
   */
  public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
  {
    $page = $page ?: Paginator::resolveCurrentPage($pageName);
 
    $perPage = $perPage ?: $this->model->getPerPage();
 
    $results = ($total = $this->toBase()->getCountForPagination())
                  ? $this->forPage($page, $perPage)->get($columns)
                  : $this->model->newCollection();
 
    return $this->paginator($results, $total, $perPage, $page, [
      'path' => Paginator::resolveCurrentPath(),
      'pageName' => $pageName,
    ]);
  }

發(fā)現(xiàn),分頁(yè)用了 \Illuminate\Contracts\Pagination\LengthAwarePaginator 構(gòu)造方法,查看這個(gè)構(gòu)造方法

?php
 
namespace Illuminate\Pagination;
 
use Countable;
use ArrayAccess;
use JsonSerializable;
use IteratorAggregate;
use Illuminate\Support\Collection;
use Illuminate\Support\HtmlString;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Pagination\LengthAwarePaginator as LengthAwarePaginatorContract;
 
class LengthAwarePaginator extends AbstractPaginator implements Arrayable, ArrayAccess, Countable, IteratorAggregate, JsonSerializable, Jsonable, LengthAwarePaginatorContract
{
  /**
   * The total number of items before slicing.
   *
   * @var int
   */
  protected $total;
 
  /**
   * The last available page.
   *
   * @var int
   */
  protected $lastPage;
 
  /**
   * Create a new paginator instance.
   *
   * @param mixed $items
   * @param int $total
   * @param int $perPage
   * @param int|null $currentPage
   * @param array $options (path, query, fragment, pageName)
   * @return void
   */
  public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])
  {
    foreach ($options as $key => $value) {
      $this->{$key} = $value;
    }
 
    $this->total = $total;
    $this->perPage = $perPage;
    $this->lastPage = max((int) ceil($total / $perPage), 1);
    $this->path = $this->path !== '/' ? rtrim($this->path, '/') : $this->path;
    $this->currentPage = $this->setCurrentPage($currentPage, $this->pageName);
    $this->items = $items instanceof Collection ? $items : Collection::make($items);
  }

如果要實(shí)現(xiàn)手動(dòng)分頁(yè),只需要使用這個(gè)構(gòu)造方法,給定參數(shù),就能達(dá)到分頁(yè)的效果

貼代碼:

public function setPage2(Request $request,$data,$prepage,$total){

    #每頁(yè)顯示記錄
    $prePage = $prepage;
    //$total =count($data);
    $allitem = $prepage *100;
    $total > $allitem ? $total = $allitem : $total;
    if(isset($request->page)){
      $current_page =intval($request->page);
      $current_page =$current_page=0?1:$current_page;
    }else{
      $current_page = 1;
    }
    #url操作
    $url = $url='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];
    if(strpos($url,'page')) $url=str_replace('page='.$request->page, '',$url);
 
    # $data must be array
    $item =array_slice($data,($current_page-1)*$prePage,$prePage);
    $paginator = new LengthAwarePaginator($item,$total,$prePage,$current_page,[
      'path'=>$url,
      'pageName'=>'page'
    ]);
 
    return $paginator;
  }

($data 為需要進(jìn)行分頁(yè)的數(shù)據(jù))

說(shuō)明:

1、在考慮到代碼的復(fù)用性,我將分頁(yè)代碼封裝到app/Controllers/Controller.php中的一個(gè)方法里面,這樣在其他控制器里只需要$this->setPage(Request $request,$data,$prepage,$total) 就能使用了,(前提:其他控制器繼承了Controller.php)

2、分頁(yè)的URL,因?yàn)槲业捻?xiàng)目的url一定會(huì)攜帶一個(gè)kw參數(shù),所以我直接用str_replace替換"page",如果是存在不攜參分頁(yè)的話,需要判斷,到底是"?page"還是"page"。(url的邏輯可以自己寫(xiě))

#分頁(yè) php

     $paginator = $this->setPage2($request,$data,25,$sum);
      $data =$paginator->toArray()['data'];

在模板中:{{$paginator->render()}}即能輸出分頁(yè)HTML,樣式如下:

二、自定義分頁(yè)樣式

在實(shí)際開(kāi)發(fā)中,不希望用戶(hù)在瀏覽時(shí)直接瀏覽最后幾頁(yè),只想用戶(hù)從前往后依次的瀏覽,如百度搜索分頁(yè),這時(shí)候,就想修改分頁(yè)的樣式,經(jīng)過(guò)一個(gè)下午的奮戰(zhàn),貼出解決過(guò)程

在上一環(huán)節(jié)中,手動(dòng)創(chuàng)建了分頁(yè),了解HTML的模板生成是render()方法,

#\Illuminate\Contracts\Pagination\LengthAwarePaginator


/**
   * Render the paginator using the given view.
   *
   * @param string|null $view
   * @param array $data
   * @return \Illuminate\Support\HtmlString
   */
  public function render($view = null, $data = [])
  {
    return new HtmlString(static::viewFactory()->make($view ?: static::$defaultView, array_merge($data, [
      'paginator' => $this,
      'elements' => $this->elements(),
    ]))->render());
  }

經(jīng)過(guò)思考,我們不去改laravel框架的源代碼,可以通過(guò)重構(gòu)render方法或者重新定義一個(gè)生成HTML模板的方法來(lái)實(shí)現(xiàn)自定義HTML模板

因?yàn)槲覀冎恍枰远xHTML模板,所以,可以創(chuàng)建一個(gè)文件,繼承\(zhòng)Illuminate\Contracts\Pagination\LengthAwarePaginator 類(lèi)

看代碼:

?php
 
namespace App\Helpers;
 
use Illuminate\Pagination\LengthAwarePaginator;
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2018/4/9
 * Time: 9:08
 */
class Newpage extends LengthAwarePaginator {
 
  public $de_page = 10; //默認(rèn)顯示分頁(yè)數(shù)
  public $pageHtml;
 
  public function newrender(){
    if($this->hasPages())
    {
 
      return sprintf("ul class='pagination'>%s %s %s/ul>",
        $this->pre_page(),
        $this->pages_num(),
        $this->next_page()
      );
    }
  }
 
  #上一頁(yè)
  public function pre_page(){
    if($this->currentPage == 1){
      //dd($this->currentPage);
      return "li class='disabled'>span>《/span>/li>";
    }else{
 
      $url = $this->path."page=".($this->currentPage-1);
      //dd($url);
      return "li>a href=".$url." rel="external nofollow" rel='prev'>《/a>/li>";
    }
  }
 
  #頁(yè)碼
  public function pages_num(){
    $pages = '';
    if($this->currentPage = 6){
      for($i = 1; $i = $this->de_page; $i++){
        if($this->currentPage == $i){
          $pages .= "li class='active'>a href=".$this->path." rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" page=".$i.">".$i."/a>/li>";
        }else{
          $pages .="li>a href=".$this->path." rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" page=".$i.">".$i."/a>/li>";
        }
      }
    }else{
      #當(dāng)前頁(yè)前邊部分
      for($i = 5; $i >=1 ; $i--){
        $url =$this->currentPage-$i;
        $pages .= "li>a href=".$this->path." rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" page=".$url.">".$url."/a>/li>";
      }
      #當(dāng)前頁(yè)
      $pages .= "li class='active'>span>".$this->currentPage."/span>/li>";
      #當(dāng)前頁(yè)后邊部分
      for($i = 1;$i  5; $i++ ){
        $nowpage =$this->currentPage+$i;
        $pages .= "li>a href=".$this->path." rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" page=".$nowpage.">".$nowpage."/a>/li>";
      }
    }
    return $pages;
 
  }
  #下一頁(yè)
  public function next_page(){
    if($this->currentPage  $this->total){
      $page =$this->currentPage+1;
      return "li>a href=".$this->path." rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" page=".$page." rel='next'>span>》/span>/a>/li>";
    }else{
      return "li class='disabled'>span>》/span>/li>";
    }
 
  }
 
}

我選擇的方法是自定義新的方法生成HTML模板,模板中通過(guò):{{$paginator->newrender()}}輸出HTML

如果選擇重構(gòu)render()方法,只需要將上面的newrender()方法做一些小變動(dòng)

public function render($view=null,$data=[]){
 
    if($this->hasPages())
    {
      return sprintf("ul class='pagination'>%s %s %s/ul>",
        $this->pre_page(),
        $this->pages_num(),
        $this->next_page()
      );
    }
  }

模板中通過(guò):{{$paginator->render()}}輸出HTML

最終效果如圖:

注意:自定義HTML后因?yàn)樾陆艘粋€(gè)類(lèi)繼承了LengthAwarePaginator類(lèi),需要將第一步手動(dòng)分頁(yè)的方法中new LengthAwarePaginator 修改為 new Newpage 參數(shù)不變。

以上這篇Laravel5.5 手動(dòng)分頁(yè)和自定義分頁(yè)樣式的簡(jiǎn)單實(shí)現(xiàn)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • PHP框架Laravel插件Pagination實(shí)現(xiàn)自定義分頁(yè)
  • laravel自定義分頁(yè)效果
  • laravel自定義分頁(yè)的實(shí)現(xiàn)案例offset()和limit()
  • laravel實(shí)現(xiàn)分頁(yè)樣式替換示例代碼(增加首、尾頁(yè))
  • Laravel手動(dòng)分頁(yè)實(shí)現(xiàn)方法詳解
  • Laravel+jQuery實(shí)現(xiàn)AJAX分頁(yè)效果
  • Laravel框架執(zhí)行原生SQL語(yǔ)句及使用paginate分頁(yè)的方法
  • laravel手動(dòng)創(chuàng)建數(shù)組分頁(yè)的實(shí)現(xiàn)代碼
  • Laravel框架自定義分頁(yè)樣式操作示例

標(biāo)簽:金華 佳木斯 郴州 阿克蘇 自貢 寶雞 通化 香港

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Laravel5.5 手動(dòng)分頁(yè)和自定義分頁(yè)樣式的簡(jiǎn)單實(shí)現(xiàn)》,本文關(guān)鍵詞  Laravel5.5,手動(dòng),分頁(yè),和,自定義,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Laravel5.5 手動(dòng)分頁(yè)和自定義分頁(yè)樣式的簡(jiǎn)單實(shí)現(xiàn)》相關(guān)的同類(lèi)信息!
  • 本頁(yè)收集關(guān)于Laravel5.5 手動(dòng)分頁(yè)和自定義分頁(yè)樣式的簡(jiǎn)單實(shí)現(xiàn)的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章