If I know the internal path of my page (e.g. 'node/1') how do I get the router name?

I need it it to generate an internal url:

$url = Url::fromRoute($router_name);

I found Url::getRouteName, but I'm not sure if this is what I need?



Have a look at PathValidatorInterface::getUrlIfValid() or the version that does not check access. That is provided by the path.validator service:

| improve this answer | |
  • Thanks. That gets me the url object, but when I try to reference $url_object->routhName I get an error: Cannot access protected property Drupal\Core\Url::$routeName. – dbj44 Jan 23 '15 at 9:57
  • Use the getRouteName() method. – Berdir Jan 23 '15 at 10:54

You can also do like this

$route_name = Url::fromUserInput($internal_path)->getRouteName();

More details : http://www.drupal8.ovh/en/tutoriels/275/drupal-8-url-tips-get-name-path-args

| improve this answer | |

As an alternative to the above solution if you are having a dynamic page use this


Using the above answer for dynamic pages will be

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.