Add css file with `$this->Html->css()` from an element not working in cakephp

Hi,

I’m trying to add a specific css file from an element to the layout in cakephp but the file doesn’t appear in the source code. However it works from a static page.

// In the layout
echo $this->element('diaporama_accueil');

// In templates/element/diaporama_accueil.php [NOT WORKING] 
$this->Html->css('subtle-slideshow.css', ['block' => true]);

// In templates/Pages/accueil.php [WORKING]
$this->Html->css('subtle-slideshow.css', ['block' => true]);

What’s the problem with doing that in an element ?

Try echo $this->Html->css(‘subtle-slideshow.css’, [‘block’ => true]);

No change with echo

Does it show up when you remove the ['block' => true] ?

If so my guess is check the layout that the element is using. Does it have a fetch block for css. This might cause it not to show up.

// the layout you are using needs this for the css to show up
  <?= $this->fetch('css') ?>

When I remove ['block' => true], it doesn’t appear neither.

As I mentioned in my first post, the weird thing is that $this->Html->css('subtle-slideshow.css', ['block' => true]) does work from a static page, but does not from my element… I really don’t understand the problem… :woozy_face:

I’ve done a lot of tests, it seems that the problem happens only when I do echo $this->element('diaporama_accueil') inside the layout.
In that case the element diaporama_accueil doesn’t to return the css to the layout.

But when I call the same echo $this->element('diaporama_accueil') from any template else, the element diaporama_accueil returns the css to the layout as expected…

Can someone explain me why ?

It’s because your $this->fetch('css') statement has already run and links already added to html head before you call $this->element('diaporama_accueil') in your layout.

1 Like