0

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?

1 Answer 1

5

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.

4
  • Thank you so much for your help and attention, and if you change this code to 'Contact'|t Will be better :) Jul 24, 2016 at 0:02
  • Done. It now matches the question.
    – Shawn Conn
    Jul 24, 2016 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, 2016 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, 2016 at 1:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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