Score:0

Load css and js assets as absolute paths during twig render

eg flag

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
cn flag
Your code works fine for me in a theme: https://ibb.co/v1BSmG1
user agent avatar
eg flag
@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?
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.