n Drupal 8 - How do I get the base path? | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

in this tuto, I'll show you how to get the base path in Drupal 8.

You can use url() to generate a base url to any route in Drupal. You can supply the <front> route which, in effect, will be your base URL.

in Twig use this :

{{ url('<front>') }}

in PHP files use this :

use Drupal\Core\Url;

$base_path = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();

Url::fromRoute() is used to create a new Url object for a URL that has a Drupal route.

Examples : 

// return https://codimth.com/node/72 for example

$path = Url::fromRoute('entity.node.canonical', ['node' => $id], ['absolute' => TRUE])->toString();

 

// return login link

$login_link = Url::fromRoute('user.login', [], ['absolute' => 'true'])->toString();

 

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook