2

I have separated my template for CodeIgniter 4 in to different parts like header ,footer & sidebar. I can include them in main view like

<?= $this->include('layouts/header') ?>

but I can't send the data to this layouts, I try following syntax as like sending data to view

<?= $this->include('layouts/header',['test'=>'hello']) ?>

but when I save and check that variable in layouts/header.php as <?=$test?> It gives error ErrorException Undefined variable: test

1 Answers1

3

That include function comes out of CodeIgniter\View\View and its second parameter is an options array, not a data array:

/**
 * Used within layout views to include additional views.
 *
 * @param string     $view
 * @param array|null $options
 * @param null       $saveData
 *
 * @return string
 */
public function include(string $view, array $options = null, $saveData = true): string
{
    return $this->render($view, $options, $saveData);
}

include is meant to be used in conjunction with View Layouts, which you've mentioned nothing about. If you just need the view as-is, you should just use what the view function returns:

echo view('layouts/header',['test'=>'hello']);
parttimeturtle
  • 1,125
  • 7
  • 22