I want to use templating in a Codeigniter-4 project.
If my controller looked like this
class Blog extends \CodeIgniter\Controller
{
public function index()
{
$data = [
'todo_list' => ['Clean House', 'Call Mom', 'Run Errands'],
'title' => "My Real Title",
'heading' => "My Real Heading"
];
echo view('blogview', $data);
}
}
I want to use a templating system which works as below:
// Create new Plates instance
$templates = League\Plates\Engine::create('/path/to/templates');
// Render a template with the given data
echo $templates->render('profile', ['name' => 'Jonathan']);
My question is - what is the best place to instantiate that $templates object?
I can repeat it in every method which I know for sure is bad practice.
.... OR ...
I could do it in the __contstructor() and assign to $this->templates and I do so for every controller where I want to use that templating. I feel like there is still a better way.
I have little experience of Laravel where I don't specifically set this $templates variable to use Blade templates instead it simply calls View(). I want to achieve something like that, if possible. I tagged laravel so that anyone with more experience in Laravel may have better understanding on how to achieve it?
What would you suggest?
PS: I am using composer autoload to load all the files.
I'm afraid I am really only a CI3 user but have read a little about CI4 and there is still a base controller you can use. You should take a look at https://codeigniter4.github.io/userguide/extending/basecontroller.html?highlight=basecontroller. You would then make your $this->templates available through all extended controllers.