Razvan Zamfir
Razvan Zamfir

Reputation: 4638

How can I use Codeigniter pagination inside Twig views?

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 add theme(s). For this purpose, I use CodeIgniter Simple and Secure Twig.

The theme's templates have the extension .twig, not .php.

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

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):

<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.

Upvotes: 1

Views: 330

Answers (1)

marcogmonteiro
marcogmonteiro

Reputation: 2162

In your controllers just do add the display of those links as a variable and then display it normally in the views.

Something like:

// Controller
$this->twig->addGlobal('pagination', $this->pagination->create_links());

// View

{{ pagination|raw }}

Upvotes: 1

Related Questions