Tập tành lấy path hiện tại và path alias trong Drupal 9

7th May 2022
Table of contents

Một số câu trả lời khác chỉ đúng trong các phiên bản Drupal 7 khi sử dụng drupal_get_path_alias(). Nhưng kể từ phiên bản Drupal 8 và 9 có có những thay đổi khác.

Đoạn snippet code bên dưới là cách giúp bạn lấy đầy đủ các Path trong Drupal 8 và Drupal 9.

Đây là code lây raw path không phải path alias

$current_path = \Drupal::service('path.current')->getPath();

Để lấy được path alias

$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);

Còn một cách khác để lấy path alias

$url = \Drupal\Core\Url::fromRoute('<current>')->toString(); 

Nếu bạn muốn lấy full URL trong Drupal

$url = \Drupal\Core\Url::fromRoute('<current>',array(),array('absolute'=>'true'))->toString();

Nếu muốn lấy path trong Twig template 

//URL trang hiện tại
{{ url('<current>') }}

//Chỉ riêng Path
{{ path('<current>') }}
Bạn thấy bài viết này như thế nào?
0 reactions

Add new comment

Image CAPTCHA
Enter the characters shown in the image.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”

Related Articles

Master list (in progress) of how to get parts of fields for use in Twig templates. I’m always having to look these up, so I thought I’d hash them out and write them down.

Litespeed Cache là plugin WordPress dùng để kết hợp với Web Server LiteSpeed nhằm tăng tốc website WordPress của bạn gấp nhiều lần

In this article, we are going to see how some tools & libraries will make people's lives easier during the development & code review process.

In this tutorial, you will learn how to improve the custom code, theme and module, and general code development by using the pre-commit hook on git

Trước khi tìm hiểu xem PHP Code Sniffer là gì thì các bạn cần phải nắm được coding convention là gì đã.