Is there any equivalent of var_export
or var_dump
available in Drupal, that would output variables directly to the console
object (FF, Chrome - console.log()
or console.info()
)?
I just don't feel like turning Devel & Themer stuff on and off every time I want to peek into variables...
1 Answer
The Drupal for Firebug module (which can be used with Chrome or Firefox) has a firep()
function built in which will log a print_r
of any variable passed to it into the Drupal for Firebug widget. That might be an option.
If you really want a console log, though, I think you'd have to write the functionality yourself. It isn't too hard though, here's a quick module I knocked up that works well for me:
File: js_debug.info
name = JS Debug
core = 7.x
File: js_debug.module
function js_debug_log($var = NULL) {
$log = &drupal_static(__FUNCTION__, array());
if ($var) {
$log[] = $var;
}
return $log;
}
function js_debug_page_alter(&$page) {
drupal_add_js(drupal_get_path('module', 'js_debug') . '/js_debug.js', 'file');
drupal_add_js(array('js_debug' => array('messages' => js_debug_log())), 'setting');
}
File: js_debug.js
(function($) {
$(function() {
if (Drupal.settings.js_debug.messages) {
for (var i = 0; i < Drupal.settings.js_debug.messages.length; i++) {
console.log(Drupal.settings.js_debug.messages[i]);
}
}
});
})(jQuery);
The above code is obviously very bare, and doesn't check to make sure console.log()
is available, etc. But it will work fine in Chrome/Firefox for any var (including arrays and objects).
To use, simply call js_debug_log($var);
from code; the variable you pass will be logged in the console as you'd expect.
-
2I edited the js_debug_page_alter function to add the js file :) Now works like a charm! Thanks a bunch Clive! Commented May 5, 2012 at 18:55
-
@Artur Sorry about that, I had that bit in a
hook_init()
function which I somehow managed to miss when I copied and pasted!– Clive ♦Commented May 5, 2012 at 21:01 -
No problem whatsoever, it's always kind of a useful lesson! Commented May 5, 2012 at 21:05
-
@Clive, is there any particular reason you are using hook_pager_alter here instead of something else? It is because it is a "late" hook in the page generation process?– mpdonadio ♦Commented May 5, 2012 at 23:54
-
@MPD That was my thinking yes. I couldn't think of another hook that would get called later, but still in time to actually be included in the current page request– Clive ♦Commented May 6, 2012 at 0:08