Skip to content

Instantly share code, notes, and snippets.

@lrobeson
Created January 17, 2017 15:24
Show Gist options
  • Save lrobeson/3d91503406e09beefe126b20616b9f8f to your computer and use it in GitHub Desktop.
Save lrobeson/3d91503406e09beefe126b20616b9f8f to your computer and use it in GitHub Desktop.
By Chaz Chumley: Add more theme template suggestions
/**
To use (WIP):
- Create a Taoxnomy term called Suggestions
- Populate with terms for what you may want to use in the template
- Add the field to whatever content types (i.e. Listing or Landing content type)
- Create a .theme function to look for the field and content type
Example:
https://github.com/forumone/CBCNY/blob/6d3f9c2c808f5fbc5eee1c08fa4bcd5545298101/web/themes/cbcny_theme/cbcny_theme.theme
**/
<?php
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function gesso_theme_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  // Test for existence of Term Section
  if (isset($variables['elements']['field_term_section'])) {
    // Grab Node and Field
    $node = \Drupal::routeMatch()->getParameter('node');
    $field = $node->get('field_term_section');
    // If field not empty then grab value and use as theme suggestions
    if (!$field->isEmpty() && $node->getType() == "section") {
      $term = $field
        ->first()
        ->get('entity')
        ->getTarget()
        ->getValue()
        ->getName();
      $suggestions[] = 'node__' . 'section__' . strtolower($term);
    }
    // If field not empty then grab value and use as theme suggestions
    if (!$field->isEmpty() && $node->getType() == "page") {
      $term = $field
        ->first()
        ->get('entity')
        ->getTarget()
        ->getValue()
        ->getName();
      $suggestions[] = 'node__' . 'page__' . strtolower($term);
    }
  }
  // Test for existence of Template field
  if (isset($variables['elements']['field_template'])) {
    // Grab Node and Field
    $node = \Drupal::routeMatch()->getParameter('node');
    $field = $node->get('field_template');
    // If field not empty then grab value and use as theme suggestions
    if (!$field->isEmpty() && $node->getType() == "listing") {
      $term = $field
        ->first()
        ->get('entity')
        ->getTarget()
        ->getValue()
        ->getName();
      $suggestions[] = 'node__' . 'listing__' . strtolower($term);
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment