hook_preprocess_page(): how to tell a views page?
-
16-10-2019 - |
Pergunta
Im writing a custom module that need to insert some javascript and css files only in a Views page.
Im using hook_preprocess_page, but I can not tell if the current page is from a view:
function mymodule_preprocess_page(&vars)
{
var_dump($vars); //output: nothings that reference the views!
if([view page])
{
drupal_add_js([...]);
drupal_add_css([...]);
// Rebuild scripts
$scripts = drupal_get_js();
$vars['scripts'] = $scripts;
// Same for css
}
}
I know i could use a template file (page-my_view_page_path.tpl.php), but the js and extra css must be included only if my module is enabled; so I like to keep this things directly inside my module code.
Ideas?
Solução
views_get_page_view()
finds out what, if any, page view is currently in use. If it returns NULL, then the current page is not a views' page.
But using drupal_add_js()
and drupal_add_css()
in a hook_preprocess_page()
won't work as expected because the variable $script
and $style
variables have already been set by template_preprocess_page()
. Views's template preprocessing (see Jeremy French's answer) is probably a better place to add your CSS and JavaScript.
Outras dicas
There is a lengthy thread on preprocessors for views here. This comment looks very simple to me.
function mymodule_theme_registry_alter(&$theme_registry) {
//dpm($theme_registry);
$theme_registry['views_view__YOUR_VIEW_NAME_HERE']['preprocess functions'][] = 'mymodule_preprocess_func';
}
// now go on and play with your new preprocess function
function mymodule_preprocess_func(&$vars) {
// etc
}
If you're in a hook_preprocess_page() then, by definition, your view has a page display and a menu path, which must be unique - so you can do this:
function mymodule_preprocess_page(&vars)
{
var_dump($vars); //output: nothings that reference the views!
if($_GET['q'] == 'my/view/path')
{
drupal_add_js([...]);
drupal_add_css([...]);
}
}
If you have arguments being passed to this page, so you need parts of $_GET['q']
, then do this instead with Drupal's arg()
function:
if(arg(0) == 'my' && arg(1) == 'view' && arg(2) == 'path')
http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/arg
For me this one works:
function MYMODULE_preprocess_page(&$vars) {
$view = (array)views_get_page_view();
if (!empty($view)) {
// do stuff
}
}
If you are adding JS or CSS to a specific callback then better to use hook_page_build()
: