4

I need to add a template suggestion for entities in a custom module, similar to how you can add one for nodes. I've seen the ones implemented in the Entity API module, but how do I hook into entity preprocessing so I can add my own?

5

I found a solution. The Entity API module defines template_preprocess_entity() such that you can add template suggestions during your own preprocessing in a custom module, like for example:

function mymodule_preprocess_entity(&$variables) {
    if($variables['elements']['#entity_type'] = "myentity") {
        $variables['theme_hook_suggestions'][] = "myentity";
    }
}

This runs preprocessing for custom entities built off the Entity API, but not for not nodes or entities built into Drupal core. In order to add template suggestions for Drupal core entities, you need to add it while using the various entity-specific preprocessing hooks provided in Drupal core. For example:

// Preprocessing for taxonomy terms
function mymodule_preprocess_taxonomy_term(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for user profiles
function mymodule_preprocess_user_profile(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for comments
function mymodule_preprocess_comment(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for nodes
function mymodule_preprocess_node(&$variables) {
  // Add template suggestion code here.
}
| improve this answer | |
  • Hey bryan, if this is the right answer to your problem you should mark it as that, even if you answered it yourself. This helps others to see this problem got solved sufficiently. – leymannx Nov 15 '16 at 17:44
  • @leymannx, thanks. I couldn't upvote my own answer, so I guess I thought I couldn't mark it correct. I've fixed it. – bryanbraun Nov 17 '16 at 5:23

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.