9

I walked through the possible hooks by using function hook_preprocess(&$vars, $hook) and only entity was available to use. Is it possible to do something like hook_preprocess_profile2_entity(), or do I have to write an if condition to check the entity type in hook_preprocess_entity()?

15

This adapts the Zen theme pattern for node preprocess functions to entities:

<?php

/**
 * Implements template_preprocess_entity().
 *
 * Runs a entity specific preprocess function, if it exists.
 */
function MYTHEME_preprocess_entity(&$variables, $hook) {
  $function = __FUNCTION__ . '_' . $variables['entity_type'];
  if (function_exists($function)) {
    $function($variables, $hook);
  }
}

/**
 * Profile2 specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_entity_profile2(&$variables, $hook) {
}

/**
 * Field Collection specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_entity_field_collection_item(&$variables, $hook) {
}
  • This is awesome. I always forget that PHP lets you do stuff like this. – mpdonadio Sep 12 '11 at 17:06
  • If you want to do it in a parent theme and inherit/override, then you'll have to dig deeper into hook_theme. Zen's hook_theme is a good example (although lengthy). – Capi Etheriel Sep 13 '11 at 15:20
  • I'd be grateful if someone showed me how I can achieve something similar outside of the theme layer! Driving me nuts... – NikLP Nov 3 '15 at 19:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.