Skip to content

Instantly share code, notes, and snippets.

@BERRAMOU
Last active March 8, 2019 15:31
Show Gist options
  • Save BERRAMOU/7068c04318904921288967199fda39c8 to your computer and use it in GitHub Desktop.
Save BERRAMOU/7068c04318904921288967199fda39c8 to your computer and use it in GitHub Desktop.
Drupal 8 Twig extension to get render the header of View.
<?php
namespace Drupal\MYMODULE\Twig;
use Drupal\views\Views;
/**
* Adds extension to render a view.
*
* @package Drupal\twig_views\Twig.
*/
class HeaderView extends \Twig_Extension {
/**
* {@inheritdoc}
*/
public function getName() {
return 'render_view_header';
}
/**
* {@inheritdoc}
*/
public function getFunctions() {
return [
new \Twig_SimpleFunction(
'render_view_header',
[$this, 'renderHeaderView'],
['is_safe' => ['html']]
),
];
}
/**
* Provides function to programmatically rendering a view with title.
*
* @param string $view
* The machine name of view to render.
* @param string $display
* The machine name of display of view to render.
* @param ...
* Any additional parameters will be passed as arguments.
*
* @return array|null
* The rendered element.
*/
public static function renderHeaderView($view, $display = NULL) {
// Get function passed arguments.
$args = func_get_args();
// Remove $view and $display from the arguments.
unset($args[0], $args[1]);
// Throw exception if the display doesn't set.
if (!isset($display) && empty($display)) {
throw new \InvalidArgumentException(sprintf('You need to specify the view display.'));
}
// Get the view machine id.
$view = Views::getView($view);
// Set the display machine id.
if (!$view->setDisplay($display)) {
throw new \InvalidArgumentException(sprintf('Invalid display ID %s.', $display));
}
// Set View arguments.
if (is_array($args)) {
$view->setArguments($args);
}
// Get Headers.
$headers = $view->display_handler->getHandlers('header');
$rendered_headers = [];
if (!empty($headers)) {
foreach ($headers as $header) {
$rendered_headers[] = $header->render();
}
}
// Return the view render.
return render($rendered_headers);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment