I have a view that is being rendered like this

$view = Views::getView('view_id');
$render = $view->render(); 
$html = \Drupal::service('renderer')->render($render);

The $html variable is being returned in the build method of a Block

public function build() {
    return array(
      '#theme' => 'theme_template',
      '#view' => $html,

Then being outputted in the twig file {{ view }}

The view is being rendered but the pagination does not use ajax instead it reloads the page with the query string ?page=1

I have found a similar question but this is for drupal 7: Use ajax not working in views block displayed programmatically

Thank you in advance!

  • You shouldn't render too early and you don't need to, templates can print render arrays. Also Views provides already a block plugin: /core/modules/views/src/Plugin/Block/ViewsBlock.php.
    – 4uk4
    Commented Feb 8, 2022 at 7:48
  • Hi @4k4, thanks for replying! I have tried to use the $render variable instead but still the ajax is not being used. Im going to look into ViewsBlock but do you have any links on how to use it? Commented Feb 8, 2022 at 7:56
  • do you have any links on how to use it? @StephanSutter you just go to /admin/structure/block and place it like any other block. You can give it visibility restriction so it only appears on certain page(s).
    – No Sssweat
    Commented Feb 11, 2022 at 11:23

1 Answer 1


Try like this

public function build() {
    $view = Views::getView('view_name');
    return [
        '#type' => 'view',
        '#name' => 'view_name',
        '#view' => $view,
        '#display_id' => 'block_1',
        '#embed' => TRUE,
        '#cache' => $view->getCacheTags(),

If not use Twig Tweak and on the block's or page's template file do

{{ drupal_view('view_name', 'block_1') }}

Twig Tweak module provides a Twig extension with some useful functions and filters that can improve developer experience.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.