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.
\Drupal::service('renderer')->renderRoot()
instead of deprecateddrupal_render()
.