2

I am building a theme for Drupal 8 that I want to make available in the drupal.org theme section. As such, I want it to conform to best practice code wise. When adding JavaScript, I notice there has been some changes. Here is how I do it:

function THEMENAME_preprocess_page (&$vars, $hook) {
  $path = drupal_get_path ('theme', 'THEMENAME');
  // Render the main scripts file.
  $local_js = array (
    '#attached' => array (
      'js' => array (
        $path . '/js/THEMENAME.js' => array ('group' => JS_THEME, 'weight' => 9999),
        '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js' => array ('group' => JS_THEME, 'weight' => 9000),
      ),
    ),
  );
  drupal_render ($local_js);
}

Is this it? the best-practice way?

Edit:

In accordance to Aneek's answer I am now including JavaScript this way:

First, I created a THEMENAME.libraries.yml:

THEMENAME-base:
  version: 1.0
  js:
    //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js: {}
    js/THEMENAME.js: {}

Then, in THEMENAME.info.yml I added the libraries:

--snip--
core: 8.x
stylesheets:
  all:
    - css/grid.css
    - css/style.css
regions:
  header: 'Header image'
  home_intro: 'Home intro'
  breadcrumbs: Breadcrumbs
  content: Content
  sidebar-main: 'Sidebar main'
libraries:
  - THEMENAME/THEMENAME-base

This method includes the JavaScript files to all pages on the site. If one needs to include on specific pages only, the preprocess_page would probably be the way to do it.

  • 1
    Btw. You should use \Drupal::service('renderer')->renderRoot() instead of deprecated drupal_render(). – kenorb Aug 5 '17 at 11:02
0

If you follow the best available themes like Adaptivetheme or Omega, they followed the yml structure and placed the JavaScript files in "omega.libraries.yml" file.

If you are using template.php then for preprocess HOOKs I think they have implemented a file with .theme extension instead of template.php. See https://www.drupal.org/node/1967614

1

As of newer versions of Drupal 8, the "js"-key (or "css") is not allowed anymore in the #attached-array. Use "libraries" instead.

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.