Since /data is a path alias for a node, Drupal shows that node instead of showing what a controller associated to that path returns. If you were to set a node path alias to /admin/config/people/accounts, Drupal would show that node instead of the accounts setting page.
If you want to change the render array used for a node, you need to implement hook_ENTITY_TYPE_view()
. You can compare $entity->id()
with the node ID to which you want add data in its render array.
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\Core\Entity\Display\EntityViewDisplayInterface;
/**
* Implements hook_ENTITY_TYPE_view().
*/
function mymodule_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
if ($entity->id() == 3) {
// Change $build.
}
}
You can also find the node ID given its path alias, for example with code similar to the following one.
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\Core\Entity\Display\EntityViewDisplayInterface;
/**
* Implements hook_ENTITY_TYPE_view().
*/
function mymodule_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
$path = \Drupal::service('path_alias.manager')->getPathByAlias('/data');
if (preg_match('/node\/(\d+)/', $path, $matches)) {
if ($entity->id() == $matches[1]) {
// Change $build.
}
}
}
See How can I get the node ID from a path alias? which also explains when to use the path_alias.manager or the path.alias_manager service.
(As a side note, if I were to use this code in sites where the content is exported from a site and imported in those sites, I would compare the node UUID with the value I expect for the node I need to handle. This works only when the node UUIDs are kept when importing content.)