Skip to content
Advertisement

Load View in Custom Helper Codeigniter 4

In CI 3 i can load view file in helper like this.

if ( !function_exists('render_admin_view') ) {
        function render_admin_view($filename, $data) {
            $ci = &get_instance();
            $dir = $ci->config->item('admin_dir');
            $ci->load->view($dir . 'common/header', $data);
            $ci->load->view($filename, $data);
            $ci->load->view($dir . 'common/menu', $data);
            $ci->load->view($dir . 'common/footer', $data);
        }
}

But in CI 4, when i use this function in my custom helper, it shows following error.

Call to undefined function get_instance()

How can i load view file in helper in CI 4 ?

Advertisement

Answer

There’s no need for any of that.

In codeigniter 4 all you need to do is:

if ( !function_exists('render_admin_view') ) {
        function render_admin_view($filename, $data) {
            $dir = config('admin_dir');
            echo view($dir . 'common/header', $data);
            echo view($filename, $data);
            echo view($dir . 'common/menu', $data);
            echo view($dir . 'common/footer', $data);
        }
}

More information about using views here: https://codeigniter.com/user_guide/outgoing/views.html?highlight=views

If you want to return the views, just store it in a variable and return the contents of those variables.

Having said this, using helpers to load views is not ideal. You want to do that in your controllers. Or if you want to render sections or even have different layouts, you should look into view layouts that codeigniter 4 provides.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement