I am using Symfony 2.3.
Currently I'm adapting my routing.yml to be using a variable that I define in parameters.yml. I choose a parameter for each client/project, however there is a time that I need it to be empty.
By default (I guess), SF do require a preceding slash before the variable.
This is my current working routing.yml:
index:
path: /{_namespace}/
defaults:
_controller: AppBundle:User:index
_namespace: %namespace%
methods: [GET]
welcome:
path: /{_namespace}/welcome
defaults:
_controller: AppBundle:User:welcome
_namespace: %namespace%
methods: [GET]
And my parameters.yml:
parameters:
# [....]
namespace: 'project1'
And this let me produce URLs like:
http://www.domain.com/project1/
http://www.domain.com/project1/welcome
However, like I've said previously, I do need to have routes like:
For that, I've tried the following (notice the exclusion of the preceding slash):
routing.yml:
index:
path: {_namespace}/
defaults:
_controller: AppBundle:User:index
_namespace: %namespace%
methods: [GET]
welcome:
path: {_namespace}/welcome
defaults:
_controller: AppBundle:User:welcome
_namespace: %namespace%
methods: [GET]
parameters.yml:
parameters:
# [....]
namespace: ''
And an exception occurs:
[Symfony\Component\Config\Exception\FileLoaderLoadException]
Cannot import resource "/home/cupaofarmacia/src/Ongagement/AppBundle/Resour
ces/config/routing.yml" from "/home/project/app/config/routing.yml".
(Malformed inline YAML string ({_namespace}/) at line 51 (near "path:
{_namespace}/").)
[Symfony\Component\Yaml\Exception\ParseException]
Malformed inline YAML string ({_namespace}/) at line 51 (near "path: {
_namespace}/").
I really need to be able to pass an empty variable at the start of the route.
Any suggestions?
Not sure there is something like conditional routes in Symfony2. What I suggest is that you create a specific route for the case the namespace will be empty.
#_namespace not empty
welcome:
path: /{_namespace}/welcome
defaults:
_controller: AppBundle:User:welcome
_namespace: %namespace%
methods: [GET]
#namespace empty
welcome2:
path: /welcome
defaults:
_controller: AppBundle:User:welcome
methods: [GET]
Noticed that the placeholder and its default value are not there now.
In the controller or in the view you just check the value of the parameter _namespace and call one of the routes.
//If you use the route in the controller, with generateUrl fonction for example
$namespace= $this->container->getParameter('_namespace');
if($namespace!= '') { //use welcome }
else { //use welcome2 }
Do the twig corresponding if you use the route in the view.
Hope it helps.