Laura
Laura

Reputation: 3383

Set template data globally in Slim v3

I've recently started building a new application with the updated Slim framework in version 3.

I usually have a few variables that I want available in every template (like username, date, etc.). In Slim v2, I used to do this by using a hook and then calling the setData or appendData methods like so:

$app->view->setData(array(
    'user' => $user
));

Hooks have been replaced by Middlewares in v3, I however do not know how to set the data on the view globally for all templates - any ideas?

Upvotes: 2

Views: 2375

Answers (2)

geggleto
geggleto

Reputation: 2625

For twig-view

$view->getEnvironment()->addGlobal($name, $value);

Upvotes: 5

Ahmed Rashad
Ahmed Rashad

Reputation: 507

This is really according to the view component you are using, Slim 3 project provide 2 components Twig-View and PHP-View

For Twig-View, you can use offsetSet, this is a basic usage example, I'm going to use that example, but with one additional line to set foo variable into the view

$container['view'] = function ($c) {
    // while defining the view, you are passing settings as array
    $view = new \Slim\Views\Twig('path/to/templates', [
    'cache' => 'path/to/cache'
    ]);

    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '', $c['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($c['router'], $basePath));

    //////////////////////////////
    // this is my additional line
    $view->offsetSet('foo', 'bar');
    //////////////////////////////

    return $view;
};

You can access that in Twig template simply by using

{{ foo }}

For PHP-View, it has different forms of passing variables to template, you can find them in here

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

// or setter
$phpView->setAttributes($templateVariables);

// or individually
$phpView->addAttribute($key, $value);

Upvotes: 9

Related Questions