«

drupal10设置页面标题

时间:2023-6-9 17:39     作者:wen     分类: 其它


要设置Drupal 10页面的标题,可以使用不同的方法,取决于您的需求和上下文。以下是一些常见的方法:

  1. 使用hook_preprocess_HOOK()来设置页面标题:
/**
 * Implements hook_preprocess_HOOK() for page templates.
 */
function mymodule_preprocess_page(&$variables) {
  // 设置页面标题
  $variables['#title'] = 'My Custom Page Title';
}

在上面的示例中,我们使用hook_preprocess_page()钩子来预处理页面模板。我们将$variables['#title']变量设置为自定义的页面标题。

  1. 使用路由参数设置页面标题:
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_preprocess_HOOK() for page templates.
 */
function mymodule_preprocess_page(&$variables) {
  // 获取当前路由匹配对象
  $routeMatch = \Drupal::service('current_route_match');

  // 获取路由参数中的标题
  $title = $routeMatch->getParameter('title');

  // 设置页面标题
  $variables['#title'] = $title;
}

在这个示例中,我们使用hook_preprocess_page()钩子获取当前路由匹配对象,并使用getParameter()方法从路由参数中获取标题。然后,我们将$variables['#title']变量设置为获取到的标题。

  1. 在自定义控制器中设置页面标题:
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

/**
 * Custom controller to set page title.
 */
class MyCustomController extends ControllerBase {

  /**
   * Page callback function.
   */
  public function content() {
    // 设置页面标题
    $title = 'My Custom Page Title';
    $response = new Response();
    $response->setContent('Page Content');
    $response->headers->set('title', $title);
    return $response;
  }

}

在这个示例中,我们创建了一个自定义控制器,并在content()方法中设置了页面标题。我们通过创建Response对象,并使用$response->headers->set('title', $title)来设置页面标题。

请根据您的具体需求选择适合的方法,并将代码放置在相应的模块或主题中。确保根据您的实际情况进行适当的命名和调整。

标签: drupal10