我想以编程方式更改Drupal 8中的页面标题,以便在主题文件中对其进行硬编码。
我正在尝试使用钩子函数preprocess_page_title,但它似乎无法理解改变标题的页面。
这是我到目前为止所拥有的:
function test_preprocess_page_title(&$variables) {
if (arg(0) == 'node/12') {
$variables['title'] = 'New Title';
}
}
我认为在一个特定页面上进行此更改的唯一方法是设置节点参数。有没有人想出一种方法来覆盖Drupal上的页面标题?
以下是预处理页面的方法:
function yourthemename_preprocess_page(&$variables) {
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
$variables['title'] = $node->getTitle();
}
}
并在您的模板page.html.twig中
{{title}}
在你的template.theme文件中添加预处理器,然后通过打印变量覆盖模板文件夹中的page-title.html.twig,如下所示:
function theme_preprocess_page_title(&$variables) {
$node = \Drupal::request()->attributes->get('node');
$nid = $node->id();
if($nid == '14') {
$variables['subtitle'] = 'Subheading';
}
}
然后{{subtitle}}
有几种解决方案可以更改页面标题
在模板上
/**
* Implements hook_preprocess_HOOK().
*/
function MYMODULE_preprocess_page_title(&$variables) {
if ($YOUR_LOGIC == TRUE) {
$variables['title'] = 'New Title';
}
}
在节点视图页面上
/**
* 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 == TRUE) {
$build['#title'] = $entity->get('field_display_name')->getString();
}
}
如果要更改用户标题,请提供样本
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();
}
}
在Controller或hook_form_alter上
if ($YOUR_LOGIC == TRUE) {
$request = \Drupal::request();
if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
$route->setDefault('_title', 'New Title');
}
}