Drupal - How do I make a theme require Jquery (for anonymous users)?
I ran in to this upgrading one of my contrib themes to Drupal 8 as I wanted jquery.once for anonymous users. Here is what I did which works great:
In herchel.libraries.yml
herchel-corescripts:
version: VERSION
js:
js/scripts.js: {}
dependencies:
- core/jquery
- core/drupal.ajax
- core/drupal
- core/drupalSettings
- core/jquery.once
Then in your theme's herchel.theme file.
function herchel_preprocess_page(&$vars, $hook) {
// Render the library as laid out in herchel.libraries.yml
$libraries['#attached']['library'][] = 'herchel/herchel-corescripts';
\Drupal::service('renderer')->renderRoot($libraries);
}
Pay mind to the indenting as well for the YML code. Though it's not really documented that well yet, you can have a look at this issue and its change log.
Replace hook_library_info() by *.libraries.yml file
Note that you also see a theoretical theme's "scripts.js" file in the code above but you may not need it. In my theme, that's what uses jquery to call custom code.
This code is probably a good reference too for the YML bits. Note that in both cases version
is at the same level as dependencies
.
I also made a list of Drupal 8 issues I encountered and took part in with my D8 upgrade.
Update:
I've fixed the code, we ran in to this issue: Replace #attached library array values with provider-namespaced strings
Note this:
$libraries['#attached']['library'][] = array('herchel', 'herchel-corescripts');
vs.this
$libraries['#attached']['library'][] = 'herchel/herchel-corescripts';
I tested and the errors went away. :)
In your theme create libraries file herchel.libraries.yml
. Into this file put:
libname:
version: 1.x
js:
js/scripts.js: {}
css:
theme:
css/styles.css: {}
dependencies:
- core/jquery
In herchel.info.yml
put:
libraries:
- herchel/libname