At moment Drupal add css class page-VIEWPATH
to the body tag. How can I add css class page-VIEWNAME
to the body tag without third party module or JQuery?
Thank you in advance!
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityAt moment Drupal add css class page-VIEWPATH
to the body tag. How can I add css class page-VIEWNAME
to the body tag without third party module or JQuery?
Thank you in advance!
It turns out, this can be done with a combination of hook_preprocess_html
and function views_get_page_view
to get a true <body>
class for a given view and display (see the API page).
So wrapping it up within the hook_preprocess_html
context, it would look something like this:
/**
* Implements template_preprocess_html().
*
* Misc page preprocess functions.
*/
function mytheme_preprocess_html(&$vars) {
// Query the view and add a class
$view = views_get_page_view();
if (
isset($view) &&
$view->name == 'actions' &&
$view->current_display == "page"
) {
$vars['classes_array'][] = 'views-actions-page';
}
}
So above, I query the view name and display and the key is $view = views_get_page_view();
. This works great for custom Views body classes per view and display.
The rendered HTML result is something like this:
<body class="html not-front logged-in no-sidebars
page-actions section-actions page-views flush-header views-actions-page">
** views-actions-page
is the class that we added with the function above.
It should be noted that the advantage of this vs. using views generated classes are that if the URL of the page changes, your custom Views class will not whereas page-actions section-actions
would change based on the URL. So using those classes could be unreliable if they are used for theming as it would have a negative ripple effect.
$view = views_get_page_view();
in drupal 8/9?
Oct 1, 2021 at 5:30
\Drupal::routeMatch()->getParameter('view_id');
You'll also need use Drupal\views\Views;
Oct 12, 2021 at 11:22
Use the following function in template.php
of your theme folder
function THEME_preprocess_views_view(&$variables){
$view = $variables['view'];
if($view->name == "YOUR_VIEW_NAME" && $view->current_display == "MACHINE_NAME_OF_VIEW"){
$variables['classes_array'][]="page-".$view->name;
}
}
you can also set some other conditions like current_path
or anything else you want.