Search code examples
phptemplatesroutesslimslim-3

Slim - Use variables of a route inside an included file


I'm using Slim 3 to build an application.

In a certain route, I include via include_once the header of the template(slim/php-view 2.2), and there is some variables that I send to the template that I need to use in the header.

Is there a way to do this?

My route:

$app->get('/', function ( $request,  $response) {
    // some code here...
    $somedata = ' this is just a test';

    return $this->renderer->render($response, "/home.phtml",[
        'somedata' => $somedata,
    ]);
})

The target template(home.phtml):

<?php include_once('myheader.php'); ?>

    <h1>This is my template</h1>
    <p> I need to use this variable <?=$somedata?> 
    in the included myheader.php file</p>

Solution

  • My bad. Reading the docs I found that I can achieve what I want using template variables, like this:

    my route:

    $templateVariables = [
        "title" => "Title"
    ];
    $phpView = new PhpRenderer("./path/to/templates", $templateVariables);
    

    my included file(myheader.php):

    <?php echo $title ?>