20

I am trying to get the node URL in a Twig template. {{ content.node_link }} returns the full link, but I only need the URL.

How do I retrieve the node URL?

  • 4
    If you look in the node template, you will see that url is an available variable. Thus simply printing {{ url }} for example will render the raw URL, /node/[nid] i.e. /node/30 without any wrapping markup. Is that what you are looking to do? – Danny Englander May 30 '16 at 16:32
27

According to Functions - In Twig Templates you can use is simple by

 {{ path('entity.node.canonical', {'node': node.id}) }}
  • 3
    This solution works, and is pretty groovy. But using {{ url }} in a node-- based twig template will give you the same result. – Eric Steinborn Aug 29 '17 at 13:20
10

In a node.html.twig you can directly use {{ url }}

<a href="{{ url }}">read more</a>

For more information read comment in core template : /core/modules/node/templates/node.html.twig :

{#
/**
 * @file
 * Default theme implementation to display a node.
 *
 * Available variables:
 * - node: The node entity with limited access to object properties and methods.
 * ...
 * - url: Direct URL of the current node.
 * ...
#}
...

<article{{ attributes }}>

  {{ title_prefix }}
  {% if not page %}
    <h2{{ title_attributes }}>
      <a href="{{ url }}" rel="bookmark">{{ label }}</a>
    </h2>
  {% endif %}
  {{ title_suffix }}
  • You should explain your answer more rather than "simply put". An explanation, such as what @Danny Englander wrote in the question comment, helps the asker and others to learn more about how you came up with your answer and how they can help themselves in the future. – mradcliffe Aug 28 '17 at 18:45
  • This is the easiest method, using a built-in variable in the node twig template. – Eric Steinborn Aug 29 '17 at 13:21
  • That should be the accepted answer – Capsule Feb 2 '18 at 1:10
6

I have found this solution that works, but is quite convoluted.

{{ path('entity.node.canonical', {'node': content['#node'].id()  }) }}
  • 4
    You can use node.id instead of content['#node'].id() – 4k4 May 30 '16 at 14:10
  • 1
    I am working in view with a display suite template and 'node' is not one of the available keys. {{ dump(_context|keys) }} gives these keys only: 'content','theme_hook_original','attributes','title_attributes','content_attributes','title_prefix','title_suffix','db_is_active','is_admin','logged_in','user','directory','settings','layout', '#cache','theme_hook_suggestions' – inalto May 30 '16 at 16:21
  • Great solution for display suite templates. @4k4 content['#node'].id() is correct for the DS context. – masterchief Jul 31 '18 at 0:58

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.