I have a view shown in two ways. Once I show it as a normal block and one time using views_embed_view()
in combination with Ajax.
For the regular block I created a views-view-list.html.twig
template in my theme adding a div
wrapper. My styling is based on this added div.
For the embedded block, this views-view-list.html.twig
block is ignored and therefor the styling is off.
Using views_embed_view()
inside a preprocess
does work the way you'd expect, but using it with Ajax ignores the templates.
How can I make sure the template is not ignored, or is there a way to add another template that is seen when embedding the view?
I have a custom module my_view_ajax
I attach the js file in my .module file:
function my_view_ajax_preprocess_node(&$variables) {
$node = $variables['node'];
//check content type
if ($node->getType() == 'article' || $node->getType() == 'issue' ) {
$variables['#attached']['library'][] = 'my_view_ajax/my_view_ajax__js';
}
}
In my .js file I use Ajax to get my views block.
const routing_url = '/custom/ajax/articles';
$.ajax({
type: 'GET',
url: routing_url,
data: 'nid='+nid,
dataType: 'html',
async: true,
complete: function (data) {
$containerContent.empty().html(data.responseText);
$containerContent.fadeIn();
$ajaxLoader.fadeOut();
}
});
In my routing.yml
I create the Ajax path
my_view_ajax.articles:
path: '/custom/ajax/articles'
defaults:
_title: 'Articles'
_controller: '\Drupal\my_view_ajax\Controller\viewsajaxController::issueArticles'
requirements:
_permission: 'access content'
And finally in my viewsajaxController.php
namespace Drupal\my_view_ajax\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;
use \Symfony\Component\HttpFoundation\Response;
class viewsajaxController extends ControllerBase {
public function issueArticles() {
$nid = 11;
$markup = \Drupal::service('renderer')->render(views_embed_view('ccr_overview', 'block_articles_view', $nid));
return new Response($markup);
}
}