I would like display a link using a route name (home) into my template. How can I do with Slim Framework Thanks
My route
<?php
// index : home
$app->get('/home', function () use ($app){
$app->render('home.php');
})->name('home');
My template
<div>
<a href="<?php echo $this->tr("home"); // This doesn't work ?>">my home link</a>
</div>
or with urlFor()
<div>
<a href="<?php echo $this->urlFor("home"); // This doesn't work ?>">my home link</a>
</div>
I got this message
=> Call to undefined method Slim\View::urlFor()
I found the solution
just add this
$app->hook('slim.before.router', function () use ($app) {
// Pass in the App so we can use urlFor() to generate routes
$app->view()->setData('app', $app);
});
An then into your template you can use this (with app not this):
<div>
<a href="<?php echo $app->urlFor("home"); ?>">my home link</a>
</div>
OR:
echo '<a href="' . Slim\Slim::getInstance()->urlFor('home') . '">home</a>';
The Slim instance is accessible through a Singleton and its getInstance
method
<a href="<?php echo Slim\Slim::getInstance()->urlFor('home'); ?>">my home link</a>
You can also specify a name if you have multiple instances of Slim
<a href="<?php echo Slim\Slim::getInstance('blog')->urlFor('home'); ?>">my home link</a>
If you want to access the urlFor method using $this
<a href="<?php echo $this->urlFor("home");">my home link</a>
Then you should create a Custom View by adding a subclass of Slim\View
containing a urlFor
method and link it to Slim
Custom class :
<?php
class CustomView extends \Slim\View
{
public function urlFor($name, $params = array(), $appName = 'default')
{
return Slim::getInstance($appName)->urlFor($name, $params);
}
}
Linking :
<?php
require 'CustomView.php';
$app = new \Slim\Slim(array(
'view' => new CustomView()
));