1

I need to create a node twig template that is just for the basic page content type that based on a custom field on the content type. We have other content type like Article, Blog, Products that do not need these specific twig template.

How would we create twig templates based on the field_type so that it only applies to the basic page content type?

Here is what we tried, but couldn't find how we could detect for the basic page content type and the value for the field_type. We tried ksm($suggestions) and ksm($variables), but it does not print which implies that the hook isn't called even after clearing cache.

function mymodule_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  // This is what we are looking for. 
  $node_bundle = $node->bundle();
  if($node_bundle == 'page') {
    // we want something like this.
    $node_type_value = $node->field_type->value;
    $node_view_mode = $node->view_mode; // not sure what this would be. 
    $suggestions[] = 'node__' . $node_bundle . '__' . $node_type_value
  }
}
  • Where have you defined $node (if you haven’t, it’s in $variables[‘node’]) – Clive Oct 21 at 17:06
1

You need to get the values first you want to work with. For example the node object is inside $variables['elements']['#node']. In the sample below field_foobar is a text field. Depending on what your field type is you may need to get the value you want a little bit differently. And also maybe sanitize it first before you use it in a template suggestion (replace spaces etc.).

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  /** @var \Drupal\node\Entity\Node $node */
  $node = $variables['elements']['#node'];
  if ($node->bundle() === 'page') {
    if (!$node->get('field_foobar')->isEmpty()) {
      $value = $node->get('field_foobar')->first()->getValue()['value'];
      $view_mode = $variables['elements']['#view_mode'];
      $suggestions[] = 'node__page__' . $view_mode . '__' . $value;
    }
  }
}
  • getting the $node from $variables['elements']['#node']; got me exactly what i needed. – usernameabc Oct 22 at 17:09

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.