Skip to content

Instantly share code, notes, and snippets.

@druman
Last active April 13, 2022 19:52
Show Gist options
  • Save druman/a4c41f113a079f0df6f716520181efc5 to your computer and use it in GitHub Desktop.
Save druman/a4c41f113a079f0df6f716520181efc5 to your computer and use it in GitHub Desktop.
Drupal 8 Add library JS
<?php
/////// ADD LIBRARY /////////
// helloworld.libraries.yml
helloworlds:
version: 1.x
js:
js/script.js: {}
dependencies:
- core/jquery
/**
* FOR ALL PAGES
* hook_page_attachments().
*/
function MODULENAME_page_attachments(array &$attachments) {
$attachments['#attached']['library'][] = 'modulename/helloworlds';
}
// FOR CUSTOM /hello page
// In custom controller /helloWorld/src/Controller/HelloWorldController.php
public function helloWorld() {
$output = array();
$output['#title'] = 'HelloWorld page title';
$output['#markup'] = 'Hello World!';
$output['#attached']['library'][] = 'helloworld/helloworlds';
return $output;
}
// add library from TWIG
{{ attach_library('MYMODULE/helloworlds') }}
// Attach external library, ex: VexJS
helloworld:
version: 1.x
js:
js/script.js: {}
dependencies:
- core/jquery
vexjs:
remote: https://github.com/HubSpot/vex
version: 2.3.2
license:
name: MIT
url: https://github.com/HubSpot/vex/blob/master/LICENSE
gpl-compatible: true
css:
theme:
https://cdn.rawgit.com/HubSpot/vex/master/css/vex.css: { type: external, minified: false }
https://cdn.rawgit.com/HubSpot/vex/master/css/vex-theme-default.css: { type: external, minified: false }
js:
https://cdn.rawgit.com/HubSpot/vex/master/js/vex.combined.min.js: { type: external, minified: true }
dependencies:
- core/jquery
<?php
namespace Drupal\helloworld\Controller;
use Drupal\Core\Controller\ControllerBase;
class HelloWorldController extends ControllerBase {
public function helloWorld() {
$output = array();
$output['#title'] = 'HelloWorld page title';
$output['#markup'] = 'Hello World!';
$output['#attached']['library'][] = 'helloworld/vexjs';
$output['#attached']['library'][] = 'helloworld/helloworld';
return $output;
}
}
/**
* @file
* Simple JavaScript hello world file.
*/
(function ($, Drupal, settings) {
"use strict";
Drupal.behaviors.helloworld = {
attach: function (context) {
vex.defaultOptions.className = 'vex-theme-default';
vex.dialog.confirm({
message: 'Are you absolutely sure you want to destroy the alien planet?',
callback: function(value) {
return console.log(value ? 'Successfully destroyed the planet.' : 'Chicken.');
}
});
}
}
})(jQuery, Drupal, drupalSettings);
@pcambra
Copy link

pcambra commented Dec 16, 2020

https://cdn.rawgit.com seems to be soon removed, https://cdn.jsdelivr.net/gh can be used instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment