In this example, we will see how to use CI build-in helpers. For this example, we will use the URL helper for generating links. The URL helper file contains functions that assist in working with URLs. We will use the URL helper function site_url()
, which returns the site URL as specified in the config file.
This example will be constructed from either of the following controllers:
application/controllers/ helperexample1.php
This controller loads the built-in CI helper URL.
$this->load->helper('url'),
The controller renders a view named helper-example1-view
application/views/helper-example1-view.php
This view will use the URL helper to generate links in the view file
Let us assume the URLs to the project root are as follows: http://mydomain.com/myproject
. http://mydomain.com/myproject/helperexample1
Now we will see how the controller loads the built-in CI URL helper so the view file will be able to use the URL helper function site_url
, which generates the links.
class Helperexample1 extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore * will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ public function index() { // Loading the url helper $this->load->helper('url'), $this->load->view('helper-example1-view'), } } /* End of file helperexample1.php */ /* Location: ./application/controllers/helperexample1 */
The view file calls the URL helper function site_url
. Since the controller loaded the URL helper, it's recognized by the view.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Menu</title> </head> <body> <table> <tr> <td><a href="<?php echo site_url('welcome'), ?>">Welcome</a></td> </tr> <tr> <td><a href="<?php echo site_url('example2/more/1/2/3'), ?>">Example2</a></td> </tr> </table> </body> </html>
3.12.107.31