How to add javascript library in Drupal 8 theme?

纵然是瞬间 提交于 2019-12-24 11:16:18

问题


I'm attempting to include a custom javascript file to manipulate my menu's in the Drupal 8 theme I am building. I followed the instructions in the Drupal 8 themeing guide, including it in my .info.yml file:

#js libraries
libraries:
- dcf/base

and defining it in my .libraries.yml file:

base:
version: 1.x
js:
    js/endscripts.js
dependencies:
    - core/drupal
    - core/underscore
    - core/backbone
    - core/jquery

and finally creating a .theme file with a hook implementation (I'm not really a PHP developer, so I mostly did a copy/paste job from the example in the guide)

<?php

function dcf_page_alter(&$page) { 
  $page['#attached']['library'][] = 'dcf/base';
}

?>

I clear the cache, log off to see the non-logged-in page (the admin view has a LOT of extra scripts and css files that it calls) and look at the source to see if my script is being loaded. All of the dependencies I listed in my library are being loaded, but not my script itself.

The script itself is just a basic test that should hide my main menu using JQuery, put into the 'strict' format the themeing guide mentions is required.

(function () {
  "use strict";
  // Custom javascript
  $(document).ready(function() {
    $("#block-dcf-main-menu").hide();
  });
})();

I'm at a loss at this point. My instinct is that the mistake is in my hook implementation, because I really don't understand Drupal's hook system, but as far as I can tell, it could still just be that they haven't finished implementing this yet for Drupal 8(I'm doing this to test Drupal 8 for my organizations upcoming website rebuild, and am currently running Drupal 8.0.x-beta2 with no additional modules installed)


回答1:


this is how i did it

my_theme.info

no library declaration

my_theme.libraries.yml

my_theme:
  version: 1.0
  css:
    theme:
      css/my_theme.css: {}
  js:
    js/my_theme.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

my_theme.theme

/*
*
*    see doc to attach library more specifically
*
* */
function my_theme_page_attachments_alter(array &$attachments) {
    $attachments['#attached']['library'][] = 'my_theme/my_theme';    
}

/js/my_theme.js

 console.log('it works!');

/css/my_theme.css

 /*smthg radical happens*/
 body{
   display:none;
 }



回答2:


The answer, as in the comment from clive was the missing {} at the end of the script. So the script declaration in mytheme.libraries.yml should be
js: js/endscripts: {}



来源:https://stackoverflow.com/questions/26512831/how-to-add-javascript-library-in-drupal-8-theme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!