Skip to content

Instantly share code, notes, and snippets.

@ezheidtmann
Created January 29, 2014 20:45
Show Gist options
  • Save ezheidtmann/8696689 to your computer and use it in GitHub Desktop.
Save ezheidtmann/8696689 to your computer and use it in GitHub Desktop.
Add a template suggestion for each context in effect (Drupal 7)
<?php
/**
* Implements hook_preprocess()
*
* For each context currently activated, add a theme suggestion for each
* existing suggestion. If you have a context called "everywhere", we don't
* generate a suggestion for that context.
*
* FIXME: This doesn't indicate which context is positioning each
* individual item. Usually this isn't a problem, but it should be fixed.
*/
function THEME_preprocess(&$vars, $hook) {
$context = context_get();
if(!empty($context['context'])) {
foreach(array_keys($context['context']) as $context_name) {
// Skip the "everywhere" context.
// TODO: generalize this to a condition check.
if ($context_name == 'everywhere') {
continue;
}
// Template suggestions must not contain dashes (so functions can
// implement them) but contexts can contain dashes. This will produce
// collisions if there are two contexts "some_thing" and "some-thing",
// for example, but if that happens, your site is pretty far off the
// rails already.
$lc_context_name = str_replace('-', '_', strtolower($context_name));
$new_suggestions = array();
$new_suggestions[] = $hook . '__context_' . $lc_context_name;
foreach ($vars['theme_hook_suggestions'] as $suggestion) {
$new_suggestions[] = $suggestion;
$new_suggestions[] = $suggestion . '__context_' . $lc_context_name;
}
$vars['theme_hook_suggestions'] = $new_suggestions;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment