4

如何从我的 .theme 文件中更改此标记?

\core\modules\search\src\Controller\SearchController.php 中的第 119 行

if (count($results)) {
   $build['search_results_title'] = array(
        '#markup' => '<h2>' . $this->t('Search results') . '</h2>',
    );
}

我想从我的搜索页面中删除“搜索结果”H2。

我能够使用搜索表单上的 _preprocess_form 函数和搜索结果上的 preprocess_search_result 更改上面的搜索表单和 H2 下面的结果列表。

是否缺少预处理功能,或者我可以使用自定义树枝模板吗?

4

3 回答 3

5

您必须更改搜索模块定义的路线。为此:

  1. 在您的mymodule.services.yml文件中定义以下内容:
    服务:
      mymodule.route_subscriber:
      类: Drupal\mymodule\Routing\RouteSubscriber
      标签:
        - {名称:事件订阅者}

  1. 创建一个扩展RouteSubscriberBase/mymodule/src/Routing/RouteSubscriber.php 上的类的类,如下所示:
    /**
     * @文件
     * 包含 \Drupal\mymodule\Routing\RouteSubscriber。
     */

    命名空间 Drupal\mymodule\Routing;

    使用 Drupal\Core\Routing\RouteSubscriberBase;
    使用 Symfony\Component\Routing\RouteCollection;

    /**
     * 监听动态路由事件。
     */
    类 RouteSubscriber 扩展 RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      公共功能 alterRoutes(RouteCollection $collection) {
        // 替换动态创建的“search.view_node_search”路由的Controller
        // 用我们自己的。
        if ($route = $collection->get('search.view_node_search')) {
          $route->setDefault('_controller', '\Drupal\mymodule\Controller\MyModuleSearchController::view');
        }
      }
    }

  1. 最后,控制器本身位于 /mymodule/src/Controller/MyModuleSearchController.php
    命名空间 Drupal\mymodule\Controller;

    使用 Drupal\search\SearchPageInterface;
    使用 Symfony\Component\HttpFoundation\Request;
    使用 Drupal\search\Controller\SearchController;

    /**
     * 覆盖路由控制器进行搜索。
     */
    类 MyModuleSearchController 扩展 SearchController {

      /**
       * {@inheritdoc}
       */
      公共功能视图(请求 $request,SearchPageInterface $entity){
        $build = parent::view($request, $entity);
        // 取消设置结果标题。
        if (isset($build['search_results_title'])) {
          未设置($build['search_results_title']);
        }

        返回$构建;
      }

    }

于 2017-06-13T13:21:15.710 回答
0

@hugronaphor 的解决方案非常完美。我希望我的搜索结果标题是“'(searchterm)'的搜索结果”,而不仅仅是“搜索结果”,@hugronaphor 描述的步骤正是这样做的。

在我的视图函数中,我把这个:

if (isset($build['search_results_title']) && isset($_GET['keys'])) {
   $build['search_results_title'] = ['#markup' => '<h2>' . t('Search results for') . ' "' . $_GET['keys'] . '"</h2>'];
}
于 2018-07-13T13:30:36.070 回答
-1

您可以覆盖 item-list--search-results.html.twig,并在此处替换标题:

  {%- if title is not empty -%}
    <h3>{{ title }}</h3>
  {%- endif -%}

只需删除该 h3。

于 2017-02-09T14:43:03.760 回答