php 核心搜索模块,更改标记

hsvhsicv  于 12个月前  发布在  PHP
关注(0)|答案(3)|浏览(87)

我想删除在core/modules/search/src/Controller\SearchController.php的第119行的搜索页面中添加的 Search results 字符串。

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

我可以使用搜索表单上的preprocess_form函数和搜索结果上的preprocess_search_result来更改上面的搜索表单和结果列表。
是否有我遗漏的预处理函数,或者我可以使用自定义模板文件?

q0qdq0h2

q0qdq0h21#

你必须改变搜索模块定义的路线。为此:
1.在mymodule.services.yml文件中定义以下内容:

services:
      mymodule.route_subscriber:
      class: Drupal\mymodule\Routing\RouteSubscriber
      tags:
        - { name: event_subscriber }

1.在/mymodule/src/Routing/RouteSubscriber. php上创建一个扩展RouteSubscriberBase类的类,如下所示:

<?php
    /**
     * @file
     * Contains \Drupal\mymodule\Routing\RouteSubscriber.
     */
    
    namespace Drupal\mymodule\Routing;
    
    use Drupal\Core\Routing\RouteSubscriberBase;
    use Symfony\Component\Routing\RouteCollection;
    
    /**
     * Listens to the dynamic route events.
     */
    class RouteSubscriber extends RouteSubscriberBase {
    
      /**
       * {@inheritdoc}
       */
      public function alterRoutes(RouteCollection $collection) {
        // Replace dynamically created "search.view_node_search" route's Controller
        // with our own.
        if ($route = $collection->get('search.view_node_search')) {
          $route->setDefault('_controller', '\Drupal\mymodule\Controller\MyModuleSearchController::view');
        }
      }
    }

1.最后,控制器本身位于/mymodule/src/Controller/MyModuleSearchController. php

<?php
    namespace Drupal\mymodule\Controller;
    
    use Drupal\search\SearchPageInterface;
    use Symfony\Component\HttpFoundation\Request;
    use Drupal\search\Controller\SearchController;
    
    /**
     * Override the Route controller for search.
     */
    class MyModuleSearchController extends SearchController {
    
      /**
       * {@inheritdoc}
       */
      public function view(Request $request, SearchPageInterface $entity) {
        $build = parent::view($request, $entity);
        // Unset the Result title.
        if (isset($build['search_results_title'])) {
          unset($build['search_results_title']);
        }
    
        return $build;
      }
    
    }
ecfsfe2w

ecfsfe2w2#

@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>'];
}
fdx2calv

fdx2calv3#

您可以覆盖item-list--search-results.html.twig,并替换标题,如下所示:

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

把这个H3去掉。

相关问题