Welcome Guest, Not a member yet? Register   Sign In
How do I use Codeigniter pagination inside Twig views?
#1

I am working on a online newspaper/blogging application with CodeIgniter 3.1.8 and Bootstrap 4. I have decided to add themes to it. The application is not HMVC, only MVC.

I thought it was a good idea to use the Twig template engine to the theme(s). For this purpose, I use CodeIgniter Simple and Secure Twig.

The public views have the extension .twig, not .php.

This part of the Posts controller is responsible with displaying the posts with pagination:

 
PHP Code:
private function _initPagination($path$totalRows$query_string_segment 'page') {
    //load and configure pagination 
    
$this->load->library('pagination');
    
$config['base_url'] = base_url($path);
    
$config['query_string_segment'] = $query_string_segment
    
$config['enable_query_strings'] =TRUE;
    
$config['reuse_query_string'] =TRUE;
    
$config['total_rows'] = $totalRows;
    
$config['per_page'] = 12;
    if (!isset(
$_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
        
$_GET[$config['query_string_segment']] = 1;
    }
    
$this->pagination->initialize($config);

    
$limit $config['per_page'];
    
$offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

    return [
'limit' => $limit'offset' => $offset];
}

public function 
index() {

      //call initialization method
    
$config $this->_initPagination("/"$this->Posts_model->get_num_rows());

    
$data $this->Static_model->get_static_data();
    
$data['base_url'] = base_url("/");
    
$data['pages'] = $this->Pages_model->get_pages();
    
$data['categories'] = $this->Categories_model->get_categories();  

      
//use limit and offset returned by _initPaginator method
    
$data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);

    
$this->twig->addGlobal('siteTitle''My Awesome Site');
    
$this->twig->addGlobal('maincss'base_url('themes/caminar/assets/css/main.css'));
    
$this->twig->display('themes/caminar/layout'$data);



If I had classic codeigniter views, I would display the pagination on page this way (I already did, in a previous version of the project):

PHP Code:
<div class="pagination-container text-center">
   <?php echo $this->pagination->create_links(); ?>
</div> 
 
But I now need a way to pass the pagination to Twig views. Adding the code above does not work, and I have not been able to find a viable alternative.
Reply
#2

You can simply add that function as part of the data array that will be sent to the view in your controller, like so:

Code:
$data['pagination'] = $this->pagination->create_links();

Then in your twig template, you echo the variable:
Code:
{{ pagination }}
Check out my blog: https://lagbaja.dev
Reply




Theme © iAndrew 2016 - Forum software by © MyBB