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();