I'm trying to link to a Drupal path like "Contact Us" in my Twig template. I've tried this code in my Twig template but I can't get any result.

<a href="{{ contact }}">{{ 'Contact'|t }}</a>

As well as this:

<a href="{{ path('contact') }}">{{ 'Contact'|t }}</a>
<a href="{{ url('contact') }}">{{ 'Contact'|t }}</a>

What is the correct way to link to an internal Drupal path in Twig?


The path() & url() Drupal Twig functions expect a route name and will not work with a Drupal path. For a relative/absolute path to /contact, you can use path()/url() respectively with the contact.site_page route:

<a href="{{ path('contact.site_page') }}">{{ 'Contact'|t }}</a>    
<a href="{{ url('contact.site_page') }}">{{ 'Contact'|t }}</a>

If you don't know your route name, what you're looking for is link()

{{ link('Contact'|t, 'base:contact', { 'class':[] }) }}

See this d.o. page for more explanation about these 3 functions and their differences.

  • Thank you so much for your help and attention, and if you change this code to 'Contact'|t Will be better :) Jul 24 '16 at 0:02
  • Done. It now matches the question.
    – Shawn Conn
    Jul 24 '16 at 0:08
  • If it is an internal link, wouldn't it have a route, and therefore be preferable to use the route name instead of the base: scheme?
    – mpdonadio
    Jul 24 '16 at 22:06
  • That's a good point, I presumed OP didn't know his route so I offered link() as an alternative.
    – Shawn Conn
    Jul 26 '16 at 1:25

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.