I'm trying to add a external CSS file. The client wants to be able to change the url from the backend. Creating a backend settings form is not an issue, but I can't seem to get the file loaded in the frontend.

My code:

function MYTHEME_library_info_build() {
  $libraries = [];
  $libraries['mylibrary'] = [
    'version' => '1.0',
    'css' => [
      'base' => [
        'https://www.mywebsite.com/css/styles.css' => [],

  return $libraries;

The fixed url will be replaced with a variable containing the value entered in the backend.

  • What’s with the keys and mention of css when you ask about JavaScript? – Kevin Jan 31 '19 at 13:53
  • Fixed it, my bad! I'm also trying to add a external CSS file and I copy/pasted that part of my code instead of the Js part. – Jeroen Jan 31 '19 at 14:48

hook_library_info_build() would be the right hook to add dynamic library definitions (definitions that depend on any run-time information) but it needs to be implemented by a module, as its documentation page says.

Modules may implement this hook to add dynamic library definitions. Static libraries, which do not depend on any runtime information, should be declared in a modulename.libraries.yml file instead.

hook_library_info_alter() can be implemented by either a module or a theme.

Allows modules and themes to change libraries' definitions; mostly used to update a library to a newer version, while ensuring backward compatibility. In general, such manipulations should only be done to extend the library's functionality in a backward-compatible way, to avoid breaking other modules and themes that may be using the library.

If there are default values you can use (for example, using a local CSS file that is then replaced from hook_library_info_alter() basing on run-time information), you can put those default values in the .libraries.yml file, and use hook_library_info_alter() to alter them.


This is what I ended up using:

 * Implements hook_library_info_alter().
function MYTHEME_library_info_alter(&$libraries, $extension) {
  if($extension == 'MYTHEME') {
    $css = theme_get_setting('theme_custom_css');
    $js = theme_get_setting('theme_custom_js');

    if(!empty($css) && substr(strrchr($css,'.'),1) == 'css') {
      $libraries['main']['css']['theme'][$css]['type'] = 'external';
      $libraries['main']['css']['theme'][$css]['weight'] = '110';
    if(!empty($js) && substr(strrchr($js,'.'),1) == 'js') {
      $libraries['main']['js'][$js]['type'] = 'external';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.