如何修改Drupal节点预览标题,替换默认"Preview"文本
Alright, let's figure out how to replace that generic "Preview" title on node edit preview pages with the actual title of the node you're previewing in Drupal. Below are two straightforward, reliable methods that work for Drupal 8, 9, and 10 (the most common current versions):
Method 1: Use the hook_preprocess_page_title() Preprocess Hook
This is my go-to approach since it targets the page title directly and keeps logic contained in your custom module or theme.
- Open your custom module's
.modulefile (or your theme's.themefile if you're working in a theme). - Add the following code, replacing
YOUR_MODULE_OR_THEMEwith the machine name of your module/theme:
/** * Implements hook_preprocess_page_title(). */ function YOUR_MODULE_OR_THEME_preprocess_page_title(&$variables) { // Check if we're on a node preview route $current_route = \Drupal::routeMatch()->getRouteName(); if ($current_route === 'entity.node.preview') { // Grab the previewed node object $previewed_node = \Drupal::routeMatch()->getParameter('node_preview'); // Make sure we have a valid node before updating the title if ($previewed_node instanceof \Drupal\node\NodeInterface) { // Replace the default "Preview" title with a custom one including the node's title $variables['title'] = t('Preview: @node_title', ['@node_title' => $previewed_node->getTitle()]); } } }
What this does:
- It checks if the current page is a node preview by matching the route name.
- It fetches the node being previewed from the route parameters.
- It replaces the default title with a formatted string that includes the node's actual title (feel free to tweak the text inside
t()to match your needs, like just@node_title (Preview)).
Method 2: Use hook_title_alter()
If you prefer a more direct title-altering hook, this works just as well:
Add this to your .module or .theme file (again, replace the placeholder name):
/** * Implements hook_title_alter(). */ function YOUR_MODULE_OR_THEME_title_alter(&$title, $context) { // Verify we're on the node preview route if (isset($context['route_name']) && $context['route_name'] === 'entity.node.preview') { $previewed_node = \Drupal::routeMatch()->getParameter('node_preview'); if ($previewed_node instanceof \Drupal\node\NodeInterface) { $title = t('Preview: @node_title', ['@node_title' => $previewed_node->getTitle()]); } } }
Final Step: Clear Drupal Cache
Whichever method you choose, don't forget to clear Drupal's cache (you can do this via the UI at Configuration > Performance, or using Drush with drush cr). This ensures Drupal picks up your new hook implementation.
Note for Drupal 7 Users
If you're still on Drupal 7, you can use hook_node_preview() to modify the preview page's title. Here's a quick snippet:
/** * Implements hook_node_preview(). */ function YOUR_MODULE_node_preview($node) { drupal_set_title(t('Preview: @title', ['@title' => $node->title])); }
内容的提问来源于stack exchange,提问作者Markus

