4

I wonder how to attach a library to a specific content type. .e.g News. I found the following code from a post and applied the "hook" to the "node" but no idea how to filter by content type. Any idea?

function fluffiness_preprocess_node(&$variables) {
  $variables['#attached']['library'][] = 'fluffiness/cuddly-slider';
}

ref: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

8

You can check content type and add libraries like this:

function fluffiness_preprocess_node(&$variables) {
  $node = $variables['node'];
  //check content type
  if ($node->getType() == 'article') {
    $variables['#attached']['library'][] = 'fluffiness/cuddly-slider'; 
  }
}
  • 1
    IMHO better use $node->bundle() directly instead of the getType() wrapper. – Insasse Jun 8 '18 at 9:18
0

I have a module by the name of amt_general

and an entity type by the name of attendees and bound is attendance

And bellow code load js just for edit and add the page of this entity and bundle.

function amt_general_form_attendees_attendance_form_alter(&$form, $form_state) {
      // Unconditionally attach an asset to the page.
      $form['#attached']['library'][] = 'amt_general/amt_scripts';
    }
//For edit page.

    function amt_general_form_attendees_attendance_edit_form_alter(&$form, $form_state) {
      // Unconditionally attach an asset to the page.
      $form['#attached']['library'][] = 'amt_general/amt_scripts';
    }

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.