I am making an app in Symfony3. Part of the application is sectioned by dynamic subdomains --- the subdomain is represented by a slug.
subdomains:
host: "{slug}.{domain}"
default:
slug: example
...
When running on local example of such route would be e.g. http://a.localhost
When I create a link in Twig, either using {{ url('route') }}
or {{ path('route') }}
, the subdomain is always forgotten, and slug in paramenter falls to default example, always making routes http://example.localhost
.
Is there a way to implicitly copy the parameters, or mark some parameters persistent, so that I do not have to make all the links include the slug like this {{ url('route', {'slug' : slug}) }}
, in order to stay on the subdomain?
Thank you
I have created a TwigExtension for the purpose of generating links within the subdomain.
I would prefer if it were possible to make some parameters "persistent" as I mentioned in the question. Those would be implicitly carried across relative paths, but possibly nulled with explicit parameter choice. If this is not possible, I consider this better option than adding the parameter manually and best option so far.
Extension class
/**
* ApplicationExtension constructor.
*
* @param Router $router
* @param RequestStack $requestStack
*/
public function __construct(Router $router, RequestStack $requestStack)
{
$this->router = $router;
$this->requestStack = $requestStack;
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('domainPath', [
$this,
'domainPath'
]),
];
}
public function domainPath($route_name, $params = [])
{
if (!array_key_exists('slug', $params)) {
$params['slug'] = $this->requestStack->getCurrentRequest()->attributes->get('slug');
}
return $this->router->generate($route_name, $params);
}
public function getName()
{
return 'application_extension';
}
Register service (DI and Tag)
application.twig.application_extension:
class: ApplicationBundle\Twig\ApplicationExtension
arguments: ["@router", "@request_stack"]
public: false
tags:
- { name: twig.extension }
Use in template
{{ domainPath('route_name') }}