Search code examples
symfonydrupaldrupal-themingdrupal-8

Explanation for url() function Drupal 8


I'm very new to drupal and have to do some real quick small work. While going through the documentation at https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates, I saw string parameter to url() function.

<a href="{{ url('view.frontpage.page_1') }}">{{ 'View all content'|t }}</a>

what is the value that url() is taking?

Infact, i'm trying to get relative path. I used

<a href="{{directory}}/solutions.html">Solutions</a>

But, it didn't work for me because {{directory}} changed each time and led to url append. Is there any best practices? Thank you for suggestions.


Solution

  • When adding a URL into a string, for instance in a text description, core recommends we use the \Drupal\Core\Url class. This has a few handy methods:

    Internal URL based on a route - Url::fromRoute(), Example: Url::fromRoute('acquia_connector.settings') Internal URL based on a path - Url::fromInternalUri(), Example: Url::fromInternalUri('node/add') External URL - Url::fromUri, Example: Url::fromUri('https://www.acquia.com') The last two methods are very similar, the main difference is, that fromInternalUri() already assumes an 'internal:' prefix, which tells Drupal to build an internal path. It's worth reading up on what prefixes are supported, for instance the ':entity' prefix can help in building dynamic URIs.

    When you need to constrict and display the link as text you can use the toString() method: Url::fromRoute('acquia_connector.settings')->toString().

    If you need additional information please ask.