I am trying to create a link in page.html.twig that points to an alias. The code {{ url('node/1') }} shows an unexpected error, whereas {{ 'node/1' }} works fine but goes to url website/node/1.

In D7, one can use <?php echo url('node/1'); ?> and be directed to the page with proper alias.

What code can be used in D8 to display correct alias url?

  • Great question, hope you don't mind I re-phrased it a bit. – stefgosselin Feb 18 '16 at 6:08

You can use getAliasByPath function to get the url alias for a path.

Put the below code in THEME_NAME.theme file.

function THEME_NAME_preprocess_page(&$variables) {
  $variables['url_alias'] = \Drupal::service('path.alias_manager')->getAliasByPath('/node/1');

Finally print the url_alias in your page.html.twig file.

{{ url_alias }}
  • I use {{ Drupal::service('path.alias_manager')->getAliasByPath('node/1') }} in page.tpl.twig show unexpected error – Rituraj Kumar Feb 18 '16 at 6:08
  • I have edited my answer, also add / before the path (/node/1). – Suresh R Feb 18 '16 at 6:16

The twig functions url and path operate on routes and not paths, so you must specify the route name and the necessary parameters.

{{ path('entity.node.canonical', {'node': 1}) }}

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.