• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating a CI service for using templating engine?

#1
Brick 
I want to understand what is the best place to create instance of $templates object. I am using Plates templating engine.

Code:
// 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']);
e.g.
Code:
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 know I could create that Plates instance in index() method but I'd have to repeat in every method OR I could assign to $this e.g. $this->templates and set it in the contructor. It still feels like is not the best method.

I have very little experience of Laravel but I have noticed I could simply use their view() method to make use of their Blade templating engine without explicitly defining layout in each controller.

I would like to achieve something similar so that I don't have to create $templates instance in each and every controller files.

I have read throught the documentation of CI-4 and I have an inkling that it might be achieveable by creating a Service (https://bcit-ci.github.io/CodeIgniter4/c...vices.html ) or pehaps simply using config files? I am not sure.

Any ideas how do I achieve that in CI-4? What do you say?
Reply

#2
Hello,

yes, the best way is certainly by creating a service to initliase the Plate class and call his render.

Something like this :

application/Config/Services.php
Code:
// ...
public static function plates(string $view, array $data = null, string $path = '/path/to/template')
{
    $templates = \League\Plates\Engine::create($path);

    return $templates->render($view, $data);
}
// ...

and in any controller action
Code:
$data = [
    'todo_list' => ['Clean House', 'Call Mom', 'Run Errands'],
    'title'     => "My Real Title",
    'heading'   => "My Real Heading"
];

// with the default template
echo \Config\Services::plates('profile', $data);

// or with another template
echo \Config\Services::plates('blogview', $data, '/path/to/template/blog');
Reply

#3
@gabpnr - Thanks very much. Let me give it a go.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.