Переопределение html.twig.html в пользовательском модуле


Согласно этому ответу на Drupal 7 , я ищу решение для Drupal 8, чтобы просто распечатать содержимое страницы в пользовательском html.twig.html .

namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class CustomModuleController extends ControllerBase {

  public function content() {

    return [
        '#theme' => 'custommodule_page',
        '#type' => 'page',
    ];
  }
}

Этот подход, похоже, работает, но я не уверен, как я могу удалить основные и тематические компоненты CSS.

Author: Community, 2015-12-23

2 answers

Вы можете полностью занять печатную страницу, если возвращаемое вами значение является расширением класса ответов Symfony.

Здесь возвращаемое значение представляет собой массив рендеринга, поэтому Drupal предполагает, что он должен отображаться на обычной HTML-странице.

Эта сложная диаграмма показывает поток запроса к ответу: D8 Render Pipeline Вы можете прочитать больше об этой диаграмме здесь: https://www.drupal.org/developing/api/8/render/pipeline

Первый вывод на этой странице документов:

Маршруты, контроллеры которых возвращают объект с ответом , обходят конвейер ниже. Они напрямую зависят от конвейера рендеринга Symfony.

Другими словами, большая часть сложности этой диаграммы охватывает случай, когда возвращаемое значение контроллера НЕ является объектом ответа. Возврат объекта ответа исключает то, что обычно делает Drupal, чтобы обернуть массив визуализации в html.html.twig file.

В ядре есть много примеров прямого возврата объект ответа. Здесь один:

public function testFeed($use_last_modified, $use_etag, Request $request) {
  $response = new Response();

  $last_modified = strtotime('Sun, 19 Nov 1978 05:00:00 GMT');
  $etag = Crypt::hashBase64($last_modified);

  $if_modified_since = strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE'));
  $if_none_match = stripslashes($request->server->get('HTTP_IF_NONE_MATCH'));

  // Send appropriate response. We respond with a 304 not modified on either
  // etag or on last modified.
  if ($use_last_modified) {
    $response->headers->set('Last-Modified', gmdate(DateTimePlus::RFC7231, $last_modified));
  }
  if ($use_etag) {
    $response->headers->set('ETag', $etag);
  }
  // Return 304 not modified if either last modified or etag match.
  if ($last_modified == $if_modified_since || $etag == $if_none_match) {
    $response->setStatusCode(304);
    return $response;
  }

  // The following headers force validation of cache.
  $response->headers->set('Expires', 'Sun, 19 Nov 1978 05:00:00 GMT');
  $response->headers->set('Cache-Control', 'must-revalidate');
  $response->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');

  // Read actual feed from file.
  $file_name = drupal_get_path('module', 'aggregator_test') . '/aggregator_test_rss091.xml';
  $handle = fopen($file_name, 'r');
  $feed = fread($handle, filesize($file_name));
  fclose($handle);

  $response->setContent($feed);
  return $response;
}
 2
Author: Steve Persch, 2015-12-23 17:25:03

Вот мой простой контроллер для пользовательского ответа страницы:

  namespace Drupal\custom_module\Controller;

  use Drupal\Core\Controller\ControllerBase;
  use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
  use Drupal\Core\Template\TwigEnvironment;
  use Symfony\Component\HttpFoundation\Response;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\DependencyInjection\ContainerInterface;

  class CustomModuleController extends ControllerBase implements ContainerInjectionInterface {

  protected $twig;

  public function __construct(TwigEnvironment $twig) {
    $this->twig = $twig;
  }

  public static function create(ContainerInterface $container) {
    return new static($container->get('twig'));
  }

  public function content(Request $request) {

    $response = new Response();

    $twigFilePath = drupal_get_path('module', 'custom_module') . '/templates/custom_module_page.html.twig';
    $template = $this->twig->loadTemplate($twigFilePath);

    $markup = $this->twig->loadTemplate($twigFilePath)->render();
    $response->headers->set('Content-Type', 'text/html; charset=utf-8');
    $response->setContent($markup);

    return $response;
  }
}
 1
Author: MΞDIΞNVΞRBINDΞR, 2015-12-27 19:20:07