I'm using Slim3 together with Twig. Now when I'm trying to "build" a link with the path_for
helper in a twig template I don't get the full URL like https://domain.tld/path/to/something
, instead it's just /path/to/something
. What am I missing?

- 191
- 1
- 8
-
possible duplicate of https://stackoverflow.com/questions/17049712/how-to-use-absolute-path-in-twig-functions – Robert Wade Oct 27 '17 at 21:17
-
don't think so, since this isn't a Twig issue really. I think it's more of a Slim router issue. Might be wrong so... – dustypaws Oct 28 '17 at 11:05
2 Answers
If you want the Twig helper path_for to return the full URL rather than just an absolute one, you need to set the basePath property on the router.
Grab the container:
$container = $app->getContainer();
Grab the router:
$router= $container->get('router');
Set the basePath:
$router->setBasePath('https://domain.tld');

- 3,975
- 1
- 15
- 23
-
`$container = $app->getContainer(); $router = $container->get('router'); $router->setBasePath(getenv('APP_HOST'));` That didn't do anything for some reason. Links are still relative in the source of the page. Changed `$container->get('settings')` to `$container->get('router')`. Since 'settings' doesn't contain the setBasePath method. Now I don't get any errors, but nothing changed either. :P – dustypaws Oct 28 '17 at 10:58
-
btw. managing _vital_ data with an `.env` file, thus getenv (which works, checked with var_dump). – dustypaws Oct 28 '17 at 11:03
I've somewhat hacked the slim/twig-view extension to get it working. So within the TwigExtension.php I've changed
public function pathFor($name, $data = [], $queryParams = [], $appName = 'default')
{
return $this->router->pathFor($name, $data, $queryParams);
}
to
public function pathFor($name, $data = [], $queryParams = [], $appName = 'default')
{
if (getenv('APP_HOST') != '') {
return getenv('APP_HOST') . $this->router->pathFor($name, $data, $queryParams);
}
return $this->router->pathFor($name, $data, $queryParams);
}
I bet that there's a more elegant way to get this fixed. But currently that fixes my problem.
This of course requires to use an .env file together with library that makes the variables accessible via getenv()
. For that I use PHPDotenv. You could tackle this from all sorts of angles, I guess.
I still don't know why @Scriptonomy's solution doesn't work. It really should. But in my case it just doesn't ... Comments as to where I might have screwed up are welcome! :)

- 191
- 1
- 8