TransWikia.com

Is it possible to pass variables as arguments to *.libraries.yml?

Drupal Answers Asked by plambre on February 25, 2021

Say I have a foo.libraries.yml defined as so:

external.bc.js:
  version: 1.x
  js:
    //players.brightcove.net/{{variable here}}/{{variable here}}/index.min.js: { type: external, minified: true}

Where {{ variable here }} is where I want to insert values when I attach the library

Then, in a hook_ENTITY_TYPE_view() I am running:

$build['#attached']['library'][] = 'brightcove/external.bc.js';

Which is where I’d also like the pass those variables. Is that possible?

One Answer

Instead of defining the library in the .libraries.yml file, you should add it using hook_library_info_build(), which is the hook to add dynamic library definitions, as in your case.

function mymodule_library_info_build() {
  $libraries = [];

  $js_path = 'the dynamic path to the external JavaScript file';
  $libraries['external.bc.js'] = [
    'version' => '1.x',
    'js' => [
      $js_path => ['type' => 'external', 'minified' => TRUE]
    ],
  ];

  return $libraries;
}

Answered by kiamlaluno on February 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP