I'm having some trouble in order to get a view's name and the display ID in a template_preprocess_node function
.
I have a custom content type and a view with two different displays.
My idea is to define a variable in the preprocess function related to the content type (using theme_preprocess__content_type_name
function), in order to use this variable in the Twig template to switch between the displays, according to the number of results.
I understand that in order to use a variable in the preprocess function, it has to be defined somehow in the template (correct me if I got this wrong).
So my question is: how can I call the view and the display in the node preprocess function?
EDIT 1: Using Hudri suggestion:
function theme_name_preprocess_node__content_type(&$variables) {
$route = \Drupal::routeMatch()->getRouteObject();
$view_id = $route->getDefault('view_id');
$display_id = $route->getDefault('display_id');
if($view_id == 'view_name' && $display_id == 'display_name'){
$counter = count($view_id->result);
$variables['count'] = $counter;
}
}
Can the variable count
be used in the Twig template in an if clause?