1

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 ?

Hamza Zafeer
  • 2,360
  • 13
  • 30
  • 42
  • You can try replace `$ci = &get_instance();` with `$ci = get_instance();` More details is here - https://stackoverflow.com/questions/58766038/get-instance-is-not-working-in-codeigniter-helper-function – Dmitry Leiko Jul 07 '21 at 14:19
  • 1
    Does this answer your question? [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Dmitry Leiko Jul 07 '21 at 14:20
  • Why don't you try this library [https://github.com/SyedMuradAliShah/codeigniter4-template-library](https://github.com/SyedMuradAliShah/codeigniter4-template-library) – Murad Ali Dec 28 '22 at 03:23

1 Answers1

0

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.

marcogmonteiro
  • 2,061
  • 1
  • 17
  • 26