Search code examples
phpviewrendercodeigniter-4

How to use CI4 parser service to render view from module


I'm trying to load views from module folder, since CI always look for views in App/View folder, how this can be overwritten to give complete path from ROOTPATH instead of APPPATH/Views

$parser = \Config\Services::parser();
$parser->setData(['variable' => $variable])->render('modules\PluginName\Views\index');

Error CodeIgniter\View\Exceptions\ViewException Invalid file: {path/to/project}/app/Config/../Views/modules/PluginName/Views/index.php


Solution

  • You are using a path relative to the default Views path.

    You could either:

    1. Edit the line below in your Config/Path.php file in CodeIgniter 4 folder structure:

    public $viewDirectory = __DIR__ . '/../Views';
    

    to

    public $viewDirectory = '/modules/PluginName/Views';
    

    From the comments in the file: This variable must contain the name of the directory that contains the view files used by your application. By default this is in app/Views. This value is used when no value is provided to Services::renderer().

    or

    2. Set it as an absolute path for that parser:

    $parser->setData(['variable' => $variable])->render('/modules/PluginName/Views/index');
    

    Notice the slash / at the begining of the path.