0

By default, Drupal 8 loads css and js libraries using relative paths.

ie: /core/modules/contextual/css/contextual.module.css

However, because I want to generate static pages to be used by another consumer, how can I have all my libraries as absolute paths instead?

I thought of using the css_alter hook and my code is below:

function rint_css_alter(&$css, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
    
    foreach ($css as $key => $value) {
        $assetOriginalPath = $css[$key]["data"];
        $css[$key]["data"] =  "https://coaching.ddev.site/$assetOriginalPath";
    }
    print_r($css);
  
}

When I view the print_r result, it seems successful.

Result:

enter image description here

However, when I remove the print_r to view the page, I still see the relative paths for the css assets.

Note: When I used the print_r, I also saw the following error:

The website encountered an unexpected error. Please try again later.<br><em class="placeholder">RuntimeException</em>: Failed to start the session because headers have already been sent

Is there a way to make css and js assets load as absolute paths? as in

http://example.com/core/modules/contextual/css/contextual.module.css
2
  • Your code works fine for me in a theme: ibb.co/v1BSmG1
    – Clive
    Commented Aug 9, 2021 at 20:53
  • @Clive not sure what the issue is. I just edited my question with my current result. Would there perhaps be another option to achieve this? Commented Aug 9, 2021 at 21:11

1 Answer 1

0

The folwing hook implemention will change the URL's to absolute URL's

/**
 * Implements hook_js_alter().
 *
 * Pass the JavaScript array to the optimizer service.
 */
function HOOK_js_alter(&$js, $assets) {
  foreach ($js as $key => $file) {
    $file['data'] = 'http://example.com/' . $file['data'];
    $file['type'] = 'external';
    $js['http://example.com/' . $key] = $file;
    unset($js[$key]);
  }
}

/**
 * Implements hook_js_alter().
 *
 * Pass the JavaScript array to the optimizer service.
 */
function HOOK_css_alter(&$css, $assets) {
  foreach ($css as $key => $file) {
    $file['data'] = 'http://example.com/' . $file['data'];
    $file['type'] = 'external';
    $css['http://example.com/' . $key] = $file;
    unset($css[$key]);
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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