whitebear
whitebear

Reputation: 12461

How to get 'path' in the symfony2 php

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

Answers (4)

SirDerpington
SirDerpington

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.

  • route name
  • parameters of the route like /blog/{page} where page should be replaced by e.g. 1
  • boolean true/false whether the generated URL should be absolute or not

Just mentioned generateUrl() because it equals the {{ path(...) }} function in Twig.

Upvotes: 1

m14t
m14t

Reputation: 460

It takes a little hunting, but you can actually track this down pretty easily.

  1. Find where the path function is added to Twig: /src/Symfony/Bridge/Twig/Extension/RoutingExtension.php#L39.
  2. Examine the getPath function. Observe that it uses the $this->generator object which is passed in with the constructor.
  3. Find where this extension is loaded in: /src/Symfony/Bundle/TwigBundle/Resources/config/twig.xml#L81

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

Alexey B.
Alexey B.

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

eevaa
eevaa

Reputation: 1457

__FILE__

Will get you the absolute path of the current file.

Upvotes: 0

Related Questions