Skip to content

Instantly share code, notes, and snippets.

@aklump
Last active October 19, 2015 22:16
Show Gist options
  • Save aklump/f8f294c4a0858ce4c2a0 to your computer and use it in GitHub Desktop.
Save aklump/f8f294c4a0858ce4c2a0 to your computer and use it in GitHub Desktop.
A handy function to add to Drupal 7 theme to determine if a renderable arrays contain output.
/**
* Checks one or more render arrays for any visible content.
*
* @param ... array One or more renderable arrays.
*
* @return bool
*/
function my_theme_has_content() {
$build = func_get_args();
// Hash the arguments so we can static cache or tests.
$key = md5(json_encode($build));
// We use some fast static caching to speed multiple calls with the same
// arguments.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast[$key] = &drupal_static(__FUNCTION__, NULL);
}
$processed = &$drupal_static_fast[$key];
if (!isset($processed)) {
if (($html = render($build))
// This first check is to remove all tags and look for text...
&& !($processed = (bool) trim(strip_tags($html)))) {
// ...but It's possible all we have are img tags, so we'll look for at
// least one image tag and assume this is content.
$processed = (bool) preg_match('/<(img).+\/>/i', $html);
}
}
return $processed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment