Làm thế nào để tạo breadcrumb trong Codeigniter -How to create breadcrumb in Codeigniter

Lượt xem: 3312

Đường dẫn là cách người dùng tiếp cận trang web của bạn một cách đơn giản. Với những trang web có chiều sâu thì việc cung cấp đường dẫn (breacrumb) là rất cần thiết.

Hầu hết người dùng trang web sử dụng trình duyệt  nút "Back" , nếu website không có đường dẫn (breacrumb) chuyển hướng tùy chọn. 

1.Tạo class file breacrumb.php trong "system/application/libraries"

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class BreadcrumbComponent {
 private $breadcrumbs = array();
 private $separator = '  >  ';
 private $start = '<div id="breadcrumb"> ';
 private $end = '</div> ';

 public function __construct($params = array()){
  if (count($params) > 0){
   $this->initialize($params);
  }  
 }
 
 private function initialize($params = array()){
  if (count($params) > 0){
   foreach ($params as $key => $val){
    if (isset($this->{'_' . $key})){
     $this->{'_' . $key} = $val;
    }
   }
  }
 }

 function add($title, $href){  
  if (!$title OR !$href) return;
  $this->breadcrumbs[] = array('title' => $title, 'href' => $href);
 }
 
 function output(){

  if ($this->breadcrumbs) {
   
   $output = $this->start;

   foreach ($this->breadcrumbs as $key => $crumb) {
    if ($key){ 
     $output .= $this->separator;
    }

    if (end(array_keys($this->breadcrumbs)) == $key) {
     $output .= '<span> ' . $crumb['title'] . '</span> ';   
    } else {
     $output .= '<a href="' . $crumb['href'] . '"> ' . $crumb['title'] . '</a> ';
    }
   }
  
   return $output . $this->end . PHP_EOL;
  }
  
  return '';
 }

}

2. Sử dụng trong controller


function TutorialCodeigniter(){
  parent::Controller();
  $this->load->library('breadcrumbcomponent');
}

public function index(){  
  /* Breadcrumb */
  $this->breadcrumbcomponent->add('Trang chủ', base_url());
  $this->breadcrumbcomponent->add('Codeigniter', base_url().'codeigniter');  
  $this->breadcrumbcomponent->add('Làm thế nào để tạo breadcrumb trong Codeigniter', base_url().'codeigniter/lam-the-nao-de...');  
  
}

3. Kết quả