Reputation: 12461
Its very simple quesion about symfony2 ,but I couldnt find an answer by searching.
I know that I can get url in twig by
{{ path('fos_user_profile_edit') }}
but how can I do the same thing in symfony2 php source cords?
thanks in advance
Upvotes: 2
Views: 3700
Reputation: 11470
It is stated in the docs how you do it. See this documentation entry.
If you want to generate a relative URL simply use:
$url = $this->generateUrl('fos_user_profile_edit');
if you however want to generate an absolute URL you want to use this:
$router = $this->container->get('router');
$url = $router->generate('blog_show', array('slug' => 'my-blog-post'), true);
//--------------------true outputs an absolute URL-------------------------/\
// http://www.example.com/blog/my-blog-post
Also taken from the documentation here
generate()
- as already mentioned here - takes 3 parameters.
/blog/{page}
where page should be replaced by e.g. 1Just mentioned generateUrl()
because it equals the {{ path(...) }}
function in Twig.
Upvotes: 1
Reputation: 460
It takes a little hunting, but you can actually track this down pretty easily.
path
function is added to Twig: /src/Symfony/Bridge/Twig/Extension/RoutingExtension.php#L39.$this->generator
object which is passed in with the constructor.We now know that we can call $this->container->get('router')
to get the generator
used in the getPath
method, and therefore our code ends up looking something like:
$this->container->get('router')->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
Upvotes: 0
Reputation: 12033
You can use router
service. In controller its ready to use generateUrl
function
/**
* Generates a URL from the given parameters.
*
* @param string $route The name of the route
* @param mixed $parameters An array of parameters
* @param Boolean $absolute Whether to generate an absolute URL
*
* @return string The generated URL
*/
public function generateUrl($route, $parameters = array(), $absolute = false)
{
return $this->container->get('router')->generate($route, $parameters, $absolute);
}
Upvotes: 2