Hướng dẫn thay đổi Title của Page trong Drupal 8 và 9

7th May 2022
Table of contents

Nếu bạn muốn hay đổi Title của Page trong Drupal 8 và 9 sử dụng snippet đơn giản thì dưới đây là một số cách bạn có thể tham khảo các cách sau đây để làm điều đó.

Sử dụng hook preprocess trong template 

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {

    if ($YOUR_LOGIC) {
        $variables['title'] = 'Custom Title';
    }
}

Sử dụng hook node trong view 

/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
    if ($YOUR_LOGIC) {
        $build['#title'] = $entity->get('field_display_name')->getString();
    } 
}

ví dụ: bạn muốn thay đổi user title

function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
    if ($entity->getEntityTypeId() == 'user') {  
        $build['#title'] = $entity->get('field_first_name')->getString();
    }
}

Sử dụng trong Controller hoặc Hook_form_altter

if ($YOUR_LOGIC) {
  $request = \Drupal::request();
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
     $route->setDefault('_title', 'New Title');
  }
} 
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ì đã.