Is this a multi-tenant app or something you intend to distribute? If not, then perhaps the way I’m doing it might work out better. My approach is hardcoding it a bit more, but still works across multiple environments.
Most of the time I’m using path_for
in my Twig views, and since that just spits out a relative URL, I’m good to go without any modifications. When I need to overcome this issue is when I need a full URL, such as in email templates or sometimes providing callback URLs to external services.
In those cases, I’ve added an entry to my settings. 'env_uri => 'https://example.com'
My settings file is unique to each of my environments (local, staging, production) so that value can conveniently change. Then in my DI container I add this variable to the Twig environment.
$view = new Slim\Views\Twig(...
$view['env_uri'] = $c->get('settings')['env_uri'];
Now, in my views in cases where I need more than just the relative path, like email templates, I concatenate the Twig variable with path_for
.
<a href="{{ env_uri }}{{ path_for(...) }}">link</a>
This approach works well for me. I use this technique for more than just this issue though. I also use it to load in callback URLs, public keys, and other variables unique to my environments that I need “globally” in Twig.