2

I am using a custom function. In a button click i want to display view page. Here i want to render my view programatically in html format. How can i do that?

This is my jquery code:

$('.view-all-content').click(function () {

  $.post("/callajax", {
    'action': 'get_data_from_view',

  }, function (data) {

    console.log(data)

    // if (data == "gg") {
    //    console.log("suc")
    // }

    $(".view-all-content-result").html(data);

  });

});

In my function.php

function get_data_from_view() {

  $view = \Drupal::service('renderer')->render(views_embed_view('article_list', 'page_5'));

  // Other code ...

  echo $view;
}
3

2 Answers 2

3

Try this

\Drupal::service('renderer')->render(views_embed_view('VIEWSID', 'DISPLAYID'));
5
  • Thanks for your reply.I am using a function.php file in my theme root folder.When i have tried with this code showing errror "this function () doesn't exist in your file functions.php".I have added use Drupal\views\Views; namespace.Is it correct?
    – salu
    Commented Aug 30, 2018 at 5:36
  • I just tested this code myself and don't need a namespace for it. The falling this is probably something else in your code ... please post your code at least the relevant part.
    – GiorgosK
    Commented Aug 30, 2018 at 5:47
  • Thanks for your response.I have copied the code to .module file.It is working now.Thanks.
    – salu
    Commented Aug 30, 2018 at 6:04
  • Hello,how to pass language code to \Drupal::service('renderer')->render(views_embed_view('article_list', 'page_5',));.I have tried with \Drupal::service('renderer')->render(views_embed_view('article_list', 'page_5',$languageCode));.But not working.My issue is when click on a button,iam getting view result in english.But in arabic page the same english result is showing.
    – salu
    Commented Sep 6, 2018 at 12:20
  • See drupal.stackexchange.com/questions/202483/…
    – mpp
    Commented Sep 28, 2018 at 13:48
2

You try install module Twig Tweak render block view twig

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

render block set arguments

{{ drupal_view('products_by_category', 'block_1', tid) }}

You can see it https://www.drupal.org/docs/8/modules/twig-tweak/twig-tweak-and-views

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